0

I'ts my first time exploring java script,Can you help me? thanks in advance
I have a problem in conditioning textboxes.
I have 2 textboxes, the textbox1 and the textbox2, I want the textbox2 to alert me a message on a onkeypress only if textbox2 is greater than textbox1. I succeeded it but the output is not what I expected. so here is what I have done.

//javascript
function validation()
{

 x = Number(document.getElementById('text1').value);
 y = Number(document.getElementById('text2').value);
 if(x < y)
 {

  alert('Invalid');
  return false;
 }

}

<!-- HTML -->
<html>
<body>
Text1:<input type="text" id="text1"  /><Br />
Text2:<input type="text" id="text2" onkeypress="return validation()" />
</body>
</html>

so the result is this:
Text1:10
Text2:11

when the text2 is 3 digits e.g. 110 the alert message appear, it should appear when I enter 11 because text1 < text2 Am I missing something? or I'm just an idiot.

  • `keypress` will fire before the value is put into the textbox. Try `change`. – Matt R Oct 01 '14 at 19:36
  • its not very effective,it work but I want the alert message to appear before text1 < text2 and cannot type anything in the text – user3505411 Oct 01 '14 at 19:44

3 Answers3

0

actually it get called on first character, and works corectly for third one, so use onchange

 <input type="text" id="text2" onchange="return validation()" />

eventually you will have to decide the console.log instead of alerting as it blocks you testing way.

A.B
  • 20,110
  • 3
  • 37
  • 71
0

you can see this example: http://jsfiddle.net/yonatanalexis22/yxub03yt/1/

var text2 = document.getElementById('text2');
text2.onchange = function(){    
 x = Number(document.getElementById('text1').value);
 y = Number(this.value);
 if(x < y)
 {    
    alert('Invalid');

 }
}
0

First: Your inputs are "text". If you want to compare numbers, change the type of the input to "number".

Second: Adding a Listener is a cleaner way of handling this.

So the HTML could look like this:

Text1:<input type="number" id="text1"  /><Br />
Text2:<input type="number" id="text2"/>

And your JavaScript like this:

document.getElementById("text2").addEventListener("change", function() {
    if($('#text1').val() < $('#text2').val()) alert();
});

This is just a short version.

Here is the JSFiddle.

Community
  • 1
  • 1
ohboy21
  • 4,259
  • 8
  • 38
  • 66