Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

live validation with javascript - onchange only triggered once

So I'm just testing something with js, basically the number in the first input has to be bigger than the number in the second input for the submit button to be activated.

The button get's disabled just right, but if I change the number it won't activate again

<!DOCTYPE HTML>
<html>
<body>
<input type='number' id='first' onchange="validateNumber()"/><br>
<input type='number' id='second' onchange="validateNumber()"/><br>
<script type="text/javascript" >
function validateNumber()
{
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;

if(first > second){
document.getElementById('sub').disabled=false;
}else{
document.getElementById('sub').disabled=true;   
}


}
</script>
<input type="submit" id="sub"/>
</body>
</html>

Edit: The arrows of the number input trigger onchange it seems, that caused the problem

like image 612
deemel Avatar asked Nov 12 '11 13:11

deemel


3 Answers

You have to add the onclick and onkeyup event in order to respond to mouse interactions and to inserts from the clipboard:

http://jsfiddle.net/wzvvN/1

<input type='number' id='first' onkeyup="validateNumber()" onclick="validateNumber()" onchange="validateNumber()" />

<input type='number' id='second' onkeyup="validateNumber()" onclick="validateNumber()" onchange="validateNumber()" />
like image 190
ComFreek Avatar answered Nov 04 '22 22:11

ComFreek


Try binding the onfocus and onblur events to.

<input type='number' id='first' onchange="validateNumber()" onfocus="validateNumber()" onblur="validateNumber()"/><br>
<input type='number' id='second' onchange="validateNumber()" onfocus="validateNumber()" onblur="validateNumber()"/><br>
like image 34
Martin Borthiry Avatar answered Nov 04 '22 20:11

Martin Borthiry


You may want to use onkeyup(), since onchange() gets called only when you switch focus to another element.

Also, your function is currently comparing strings. Use parseInt to convert to an integer and then compare. The following code works for me:

<html>
<body>
<input type='number' id='first' onkeyup="validateNumber()"/><br>
<input type='number' id='second' onkeyup="validateNumber()"/><br>
<script type="text/javascript" >
function validateNumber()
{
  var first = parseInt(document.getElementById('first').value, 10);
  var second = parseInt(document.getElementById('second').value, 10);

  if(first > second){
    document.getElementById('sub').disabled=false;
  } else {
    document.getElementById('sub').disabled=true;   
  }
}
</script>
<input type="submit" id="sub" disabled="disabled" />
</body>
</html>
like image 3
AbdullahC Avatar answered Nov 04 '22 22:11

AbdullahC