Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I can't get value of label with jQuery and JavaScript?

I have a usual label

<label class="mytxt"  style="color: #662819;" id ="telefon"></label> 

I am setting a value like this:

document.getElementById('telefon').innerHTML = userDetails.phone; 

after a label has some value like "123".

In a pagesource, I have a label without setted value inside "><" but I see as output it alright:

pagesource: <label class="mytxt"  style="color: #662819;" id ="telefon"></label> 

My problem is when I like to GET a value. I tried standards like:

value = $("#telefon").val();  document.getElementById('telefon').value  

Nothing works, value is always "not defined". Why is this so, even if I see it in the browser?

like image 330
r.r Avatar asked Oct 07 '13 15:10

r.r


People also ask

How do I get text from labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants.

How do I set the value of a element in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


2 Answers

You need text() or html() for label not val() The function should not be called for label instead it is used to get values of input like text or checkbox etc.

Change

value = $("#telefon").val();  

To

value = $("#telefon").text();  
like image 195
Adil Avatar answered Sep 23 '22 19:09

Adil


Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html()  // or $('#telefon').text() 

or

var telefon = document.getElementById('telefon'); telefon.innerHTML; 

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement'); var label = $( el.prop('labels') ); // label.html(); // el.val(); // blah blah blah you get the idea 
like image 43
Dan Heberden Avatar answered Sep 20 '22 19:09

Dan Heberden