Answer to Question #32907 in AJAX | JavaScript | HTML | PHP for Justin

Question #32907
[code]I am having trouble with the code below because I am trying to call the text field input type so that whenever someone enters a number above 10 it responds with the alert shown below, but I am having a problem because whenever I input a number greater than 10 in the text field it still replies with "the number is less than 10"??? What am I doing wrong? FYI I am a beginner javascript learner //Variables
var txtInput = document.getElementById('txtInput');
//Functions
function submitNum()
{
if (txtInput <= 10)
{
alert("The number is less than 10");
}
else
{
alert("The number is greater than 10");
}
}
[/code]
1
Expert's answer
2013-07-09T08:18:14-0400
Solution. 
<html>
<head>
<title>JavaSscript</title>
</head>
<script type="text/javascript">
function submitNum()
{
var txtInput = parseFloat(document.getElementById('txtInput').value);
if (txtInput < 10)
{
alert("The number is less than 10");
}
else if(txtInput > 10)
{
alert("The number is greater than 10");
}
else
alert('The number is equal to 10');
}


</script>
<body>
<input type="text" placeholder="Type any number" id="txtInput" />
<input type="button" onclick="submitNum()" value="Submit" />
</body>
</html>


Where have you done errors ?
1. When you do click, it calls only function submitNum() without other definitions. So you should insert needed variables in the function.
2. document.getElementById returns only DOM node (not a value from input tag), so you should take value. How can you do this ? That’s easy – use property document.getElementById('txtInput').value. But it is not the end. It returns only string. To get a number use function parseFloat() or parseInt().

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Justin
09.07.13, 15:31

Thanks so much for your help!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS