why I can't get value of label with jquery and javascript?

r.r picture r.r · Oct 7, 2013 · Viewed 126.8k times · Source

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?

Answer

Adil picture Adil · Oct 7, 2013

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();