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,741
  • 16
  • 57
  • 94

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
  • 104
  • 1
  • 9
matt b
  • 138,234
  • 66
  • 282
  • 345
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,981
  • 12
  • 120
  • 134
0
$('.guess').keyup(function() { 
    if ($.trim( this.value ) == "foo") {
        var clicks = $('.clicks').text();
        alert('Correct! You guessed it in ' + clicks + ' clicks.');
        location.reload();
    }
});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
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,991
  • 10
  • 71
  • 77