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 eg 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.
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.
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');
}
}
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.