Doruk Ayar
Doruk Ayar

Reputation: 344

How Can I use form items in javascript

I want to use HTML form elements in JavaScript. I used them like this but it doesn't work:

<form name="M">
  <input name="in1" type="text" id="in1">
  <input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<script src="script.js"></script>

...and the JavaScript code was like this:

   var s1 = 60;

   function f1() {
     ``
     if (document.M.elements[0] == s1) {
       window.location = 'tick.htm';
     } else {
       window.location = 'cross.htm';
     }
   }

What is wrong here?

Upvotes: 1

Views: 60

Answers (1)

dhk
dhk

Reputation: 87

Just to give some clarification on why this was not working. In the test, document.M.elements[0] is a reference to the input object, not the value of the input. Using document.M.elements[0].value gives us the current value of the input.

//Ignore this, for display only.
function output(msg) {
  var element = document.getElementById('output');
  element.innerHTML = msg;
};



function f1() {
  var s1 = 60;
  if (document.M.elements[0].value == s1) {
    output('Pass');
  } else {
    output('Fail');
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <form name="M">
    <input name="in1" type="text" id="in1">
    <input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
  </form>
  <b id="output"></b>
</body>

</html>

Upvotes: 1

Related Questions