简体   繁体   English

如何在JavaScript中使用表单项

[英]How Can I use form items in javascript

I want to use HTML form elements in JavaScript. 我想在JavaScript中使用HTML表单元素。 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: ...而JavaScript代码是这样的:

   var s1 = 60;

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

What is wrong here? 怎么了

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. 在测试中, document.M.elements[0]是对input对象的引用,而不是inputvalue Using document.M.elements[0].value gives us the current value of the input. 使用document.M.elements[0].value给我们输入的当前值。

 //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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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