0

I'm trying to get the value from the HTML tag. Not the text itself, but the attribute value. What am I doing wrong?

$('label').click(function() {
    $('p').text(($(this).val()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label value="hello">click</label>
<p></p>

5
  • 1
    As a note: value isn't valid attributes for label. Valid attributes are for, the common Global attributes and custom data attribute (data-*) Commented Aug 9, 2016 at 14:07
  • Use data-* it allows you to use any arbitrary string. ex. data-value="hello" Commented Aug 9, 2016 at 14:08
  • @zer00ne What do you mean use data-*? Put it where value is? How would I get the value back in JQuery? Commented Aug 9, 2016 at 14:10
  • jQuery: .data(key) [...]Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.[...] Commented Aug 9, 2016 at 14:12
  • @Jimenemex See my answer. Commented Aug 9, 2016 at 14:12

4 Answers 4

3

labels don't have values, input and other form elements can have values. So in your case it is jQuery's attr function, to receive attribute values. And there is no need of the additional brackets around this getter.

$('label').click(function() {
    $('p').text($(this).attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label value="hello">click</label>
<p></p>

Sign up to request clarification or add additional context in comments.

Comments

2

Use data-* it allows you to use any arbitrary string. ex. data-value="hello". This is valid and universal on on any element AFAIK. The jQuery method to use is .data()

$('label').click(function() {
    $('p').text($(this).data('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-value="hello">click</label>
<p></p>

Comments

2

You may do like this in pure JS;

var lab = document.getElementsByTagName("label")[0],
    pel = document.getElementsByTagName("p")[0];
lab.onclick = e => pel.textContent = e.currentTarget.getAttribute("value");
<label value="hello">click</label>
<p></p>

Comments

0
$('label').click(function() {
    var value = $(this).attr('value');
});

Also, I don't think value is a valid attribute on a label element.

Without jQuery...

Array.from(document.querySelectorAll('label')).forEach((label) => {
   label.addEventListener('click', () => {
      let value = label.getAttribute('value');
   });
});

3 Comments

What about a div? Does that have a value attribute?
@Jimenemex They are generally on input elements.
@Jimenemex no div elements only have global attributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.