Joshua Joshua - 3 months ago 7
Javascript Question

JQuery click event only working first time

I am trying to make a dial pad just for the heck of it, the only problem I have ran into so far is that when a key is clicked it will put the corresponding number in the input box, but it won't put another one after that. I have looked at a lot of other posts, because other people have the same problem, but it seems that none of those solutions relate to my problem. Thanks in advance!

The "1" button is the only one I have functioning right now because I am waiting to implement the others until I fix my problem.




var inp = $('#dialer');
var nmbr = inp.val();
var key1 = $('#111');

key1.on('click', function(){
inp.val(nmbr + 1)
});


JSfiddle: https://jsfiddle.net/a4suk0rs/

Answer

This is because you're setting var nmbr = inp.val(); only once, so that variable will only ever contain the elements' initial value. Change your code to this:

var inp = $('#dialer');
var nmbr = inp.val();
var key1 = $('#111');

key1.on('click', function(){
  nmbr = inp.val(); // reset the `nmbr` var to the current value of `$('#dialer')`
  inp.val(nmbr + 1)
});