user3760741
user3760741

Reputation: 163

Need to get text value of an element in jQuery

I am using jQuery mobile. What i am trying to do is that when a user clicks the <li> element it transfers him to the linked page and then displays an alert which contains the text of the list element that he clicked. Unforunately, my implementation here is only displaying an empty alert box

<script>
var course;

$('body').on('click','.hello',function(){
    course = $(this).text();

});

    function loadCourse(){

    alert(course);

    $.get(
        "getCourses.php?course="+course,
        function( data ){
            $('#list1').html( data )
            .listview( 'refresh' );
        }
        );      
    }

$(function(){
  $( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
    if(window.location.href.indexOf('#page1') !== -1){
      loadCourse();

    }
  });
});

</script>
<div data-role="page" id="abc">
    <ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true">
    <li class="hello"><a href="#page1">Hello World</a></li>
    <li class="hello"><a href="#page1">Bye Bye</a></li>
    </ul>
</div>
<div data-role="page" id="page1">
    <ul data-role="listview" data-theme="a" data-split-theme="b" data-split-icon="plus" data-inset="true" id="list1">
    </ul>   
</div>

Upvotes: 0

Views: 68

Answers (4)

Rahlon
Rahlon

Reputation: 29

You can use "this" to get the correct reference.

$(function(){
    $('li').click(function(e){
        alert($(this).text());
    });
});

jsfiddle: http://jsfiddle.net/CMt9h/3/

you can also use the event argument to get the target:

$(function(){
    $('li').click(function(e){
        alert($(e.target).text());
    });
});

jsfiddle: http://jsfiddle.net/CMt9h/4/

Upvotes: 0

Florian Gl
Florian Gl

Reputation: 6014

As AndiPower said the course variable is empty due to the page reload. If you want this page reload, but still want to display the selected value on the next page you can do:

  • Submit the value to the server and load it in js ready
  • Add it as an url parameter to the href and read it in js ready
  • Store it in a cookie

Upvotes: 0

AndiPower
AndiPower

Reputation: 853

Your alert box is empty, because the variable course has no value!

Why?

Your page gets reloaded, when you click on a link. The course variable is then empty, because variable values won't be stored for the next request. HTTP is stateless!

What to do? Your page should not get reloaded. Try something like:

$('li').click(function(e){
    alert($(this).html());
    return false;

});

Upvotes: 2

EduSanCon
EduSanCon

Reputation: 1929

course = $(this).find("a").text();

Upvotes: 0

Related Questions