简体   繁体   English

从html表单到javascript

[英]from a html form to javascript

I have a form that requires three inputs as follows: 我有一个表格,需要三个输入如下:

  <form>
    <input name="mn" 
           type="number"
           min="1"
           value="1">
    <input name="mx" 
           type="number"
           min="2"
           value="10">
    <input name="step" 
           type="number"
           min="1"
           value="1">
    <input onclick="myfunc()"
           type="submit"
           value="calculate">
  </form>

all i require is to be able to access the three fields directly in javascript. 我需要的是能够直接在javascript中访问这三个字段。 I do not need to pass the information anywhere else. 我不需要在其他任何地方传递信息。

Could anyone point me in the right direction? 有人能指出我正确的方向吗? I have read examples where there has been one input, but not multiple. 我已经阅读了有一个输入但没有多个输入的示例。

  <script type="text/javascript">
    function myfunc() {
    var mn = document.getElementsByName("mn")
    var mx = document.getElementsByName("mx")
    var step = document.getElementsByName("step")
    alert((mn + mx) / step)
    }
  </script>

Give your form an id like so 给你的表单一个像这样的id

<form id="myForm">

The other thing to watch out for is that the is that the value attribute is a string so adding the two values concatenates them rather than summing them. 需要注意的另一件事是, value属性是一个字符串,因此添加两个值会连接它们而不是将它们相加。

Try instead 试试吧

var frm = document.forms["myForm"];

var _mn = parseInt( frm["mn"].value );
var _mx = parseInt( frm["mx"].value );
var _step = parseInt( frm["step"].value );

var result = ( _mn + _mx ) / _step;

I'd start with giving each input an id then i could use: 我开始给每个输入一个id然后我可以使用:

var min = document.getElementById('mn')

and so on. 等等。 To access the value you simply would call 要访问您只需调用的值

min.value

Also there is no point in removing the i from min and the a from max. 从min和a中删除i也没有意义。 That is not optimized just hard to read and understand. 这并没有优化,只是难以阅读和理解。

if u need to access to the values of the inputs change your code to: 如果您需要访问输入值,请将代码更改为:

function myfunc() {
  var mn = document.getElementsByName("mn")[0];
  var mx = document.getElementsByName("mx")[0];
  var step = document.getElementsByName("step")[0];
  // you may need to validate your values here, like step.value != 0
  alert((mn.value + mx.value) / step.value)
}

Try this: 尝试这个:

  <script type="text/javascript">
    function myfunc() {
    var mn = document.getElementsByName("mn")[0].value;
    var mx = document.getElementsByName("mx")[0].value;
    var step = document.getElementsByName("step")[0].value;
    var top = mn / mx;
    alert(top / step);
    }
  </script>

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

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