[英]Passing parameters to JavaScript function from a form
I am having trouble trying to figure out how to do this. 我无法弄清楚如何做到这一点。 I want to, using fields in a form as variables call a JavaScript function.
我想,使用表单中的字段作为变量调用JavaScript函数。
I have this: 我有这个:
<form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Joseph Swanson</option> <option value="4">Glenn Quagmire</option> </select> </form>
from an example but what I need is this, but doesn't work: 从一个例子,但我需要的是这个,但不起作用:
<form onsubmit="myFunction(this.num_cluster)"> Num. Cluster: <input type="text" id="num_cluster"> <input type="submit"> </form>
Cloud someone help me ? 云有人帮帮我吗? Thanks :)
谢谢 :)
Change id
to name
- after that you can access value of input field 将
id
更改为name
- 之后您可以访问输入字段的值
function myFunction(form, event) { event.preventDefault(); alert(form.num_cluster.value); }
<form onsubmit="return myFunction(this, event)"> Num. Cluster: <input name="num_cluster" type="text"> <input type="submit"> </form>
As problem is little more interesting - we can extend our method onsubmit 问题更有趣 - 我们可以在提交时扩展我们的方法
function s(form, event) { event.preventDefault(); var values = Array.prototype.slice.call(form.elements) // as form elements are not an array .filter(function(element) { return element.type !== 'submit'; // I don't need submit button }) .map(function(element) { return (element.name + ': ' + element.value); // get name and value for rest form inputs and assign them to values variable }); alert('values => ' + values.join(', ')) // finish }
<form onsubmit="return s(this, event)"> <p>Foo: <input type="text" name='foo' /> </p> <p>Bar: <input type="text" name='bar' /> </p> <p>Baz: <select name='baz'> <option value="lorem">lorem</option> <option value="ipsum">ipsum</option> </select> </p> <p> <input type="submit" /> </p> </form>
function myFunction(){
var value=document.getElementById("num_cluster").value;
/// value has the actual thing that you need
//... rest of your code
}
you can use this statement even in onsubmit event by directly writing java script there. 即使在onsubmit事件中也可以通过直接在那里编写java脚本来使用此语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.