$(this).val() not working to get text from span using jquery

JqueryHtml

Jquery Problem Overview


Giving this html, i want to grab "August" from it when i click on it:

<span class="ui-datepicker-month">August</span>

i tried

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).val();
    alert(monthname);
});

but doesn't seem to be working

Jquery Solutions


Solution 1 - Jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

Solution 2 - Jquery

I think you want .text():

var monthname = $(this).text();

Solution 3 - Jquery

To retrieve text of an auto generated span value just do this :

var al = $("#id-span-name").text();    
alert(al);

Solution 4 - Jquery

-None of the above consistently worked for me. So here is the solution i worked out that works consistently across all browsers as it uses basic functionality. Hope this may help others. Using jQuery 8.2

  1. Get the jquery object for "span".
  2. Get the DOM object from above. Using jquery .get(0)
  3. Using DOM's object's innerText get the text.

Here is a simple example

var curSpan = $(this).parent().children(' span').get(0);
var spansText = curSpan.innerText;

HTML

<div >
<input type='checkbox' /><span >testinput</span> 
</div>

Solution 5 - Jquery

You can use .html() to get content of span and or div elements.

example:

    var monthname =  $(this).html();
    alert(monthname);

Solution 6 - Jquery

Here we go:

$(".ui-datepicker-month").click(function(){  
var  textSpan = $(this).text();
alert(textSpan);   
});

Hope it helps;)

Solution 7 - Jquery

.val() is for input elements, use .html() instead

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryMatthew JonesView Answer on Stackoverflow
Solution 3 - JqueryHolyknightView Answer on Stackoverflow
Solution 4 - JqueryFarjadView Answer on Stackoverflow
Solution 5 - JqueryAriView Answer on Stackoverflow
Solution 6 - JquerypraguanView Answer on Stackoverflow
Solution 7 - JquerygraycrowView Answer on Stackoverflow