0

When the correct string, foo, is entered into .guess I am trying to pull the value from .clicks and pass it into an alert. When I load the page with my current code (below) the alert reads Correct! You guessed it in clicks.. Why is the clicks variable not being passed?

Thanks

jQuery:

$('.guess').keyup(function() { 
    if ($('.guess').val() == "foo") {
        var clicks = $('.clicks').val();
        alert('Correct! You guessed it in ' + clicks + ' clicks.');
        location.reload();
    }
});

HTML:

<div class="bar">
    <h2 class="clicks">0</h2>
    <input type="text" class="guess" />
</div>
conbask
  • 9,351
  • 15
  • 53
  • 91

4 Answers4

4

.val() is primarily used for getting the value of form input elements.

I think you want to use $(".clicks").text(), OR $(".clicks").html(),which will return "0".

nafischonchol
  • 82
  • 1
  • 9
matt b
  • 135,500
  • 64
  • 278
  • 339
2
$('.guess').keyup(function() { 
    if ($('.guess').val() == "foo") {
        var clicks = $('.clicks').text(); // .text() instead of .val()
        alert('Correct! You guessed it in ' + clicks + ' clicks.');
        location.reload();
    }
});
Zoltan Toth
  • 46,038
  • 11
  • 115
  • 133
0
$('.guess').keyup(function() { 
    if ($.trim( this.value ) == "foo") {
        var clicks = $('.clicks').text();
        alert('Correct! You guessed it in ' + clicks + ' clicks.');
        location.reload();
    }
});
thecodeparadox
  • 84,459
  • 21
  • 136
  • 161
0

Working demo click here :) http://jsfiddle.net/QSrWs/

please use api: .text()

This will help you to understand the difference: Difference between val() and text()

Val() works on input elements (or any element with a value attribute?) and text() will not work on input elements. Val() gets the value of the input element -- regardless of type. Text() gets the innerText (not HTML) of all the matched elements:

Hope this helps,

code

$('.guess').keyup(function() { 
    if ($('.guess').val() == "foo") {
        var clicks = $('.clicks').text();//$('.clicks').val();
        alert('Correct! You guessed it in ' + clicks + ' clicks.');
        location.reload();
    }
});​
Community
  • 1
  • 1
Tats_innit
  • 33,645
  • 9
  • 68
  • 76