简体   繁体   中英

javascript odd/even in a form

I am unable to make simple javascript that take a number in the textbox and whne the button is clicked it returns the result.

    <html>
<head>

<body>

<form>
<input id = "evenoddinput" >

<input type="button" value="check" OnClick="check();">
</form>
<script>
function check()
{
   var v=document.getElementById("evenoddinput").value;

   if(v%2==0)
   {
     } document.write("Even");

    else
    {
     document.write("odd");
    }


}
</script>

</body>
</html>

Correct syntax to select element by id attribute is getElementById not getValueById .

Also use console.log() for debugging.

 function check() { var v = document.getElementById('evenoddinput').value; if (v % 2 == 0) { console.log("Even"); } else { console.log("odd"); } } 
 <form> <input id="evenoddinput"> <input type="button" value="check" OnClick="check();"> 

Your code is wrong it must be

var v=document.getElementById("evenoddinput").value;

Not

var v=document.getValueById(evenoddinput).value; 

It is not recommended to write into page using document.write . Because it will replace entire page content. It is better to use a result field and write result to this field as innerHTML .

 function check() { var v = document.getElementById('evenoddinput').value; var result; if (v % 2 == 0) { result = "Even"; } else { result = "odd"; } document.getElementById("result").innerHTML = result; } 
 <input id="evenoddinput"> <input type="button" value="check" OnClick="check();"> <div id="result"></div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM