7

I'm working on a form, and I want to get in real time the current value of an input field of type number, as this one :

$(":input").bind('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

<p id="potential">Potential reward : <b id="reward"></b></p>

But nothing happen when I run it. It says that the value of coins is null. I don't know what I am doing wrong... Anyone could help ?

2 Answers 2

11

You could use the following:

$(document).on('input', '#coin', function(){
    var coins = $("#coins").val();
    $("#reward").text(coins);
})
Sign up to request clarification or add additional context in comments.

Comments

2

Code shown works fine when user makes edits.

If you need it to display when page loads just trigger one of the events

$(":input").on('keyup mouseup', function () {
  var coins = $("#coins").val();
  $("#reward").text(coins);
}).trigger('mouseup');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="coins" type="number" name="coins" value="1" max="999" min="1">

<p id="potential">Potential reward : <b id="reward"></b></p>

Note that bind() is deprecated in favor of using on()

3 Comments

I saw that the snippet is working well... I don't understand why my code is not working on my own, surely problems with something else. I will try to search again. Thanks anyway for your help :)
We can't help fix it without a way to reproduce the problem
I finally found my error :) It was just an issue of id that was already used :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.