Javascript javascript将文本输入传递给onclick处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7427041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:13:26  来源:igfitidea点击:

javascript passing text input to a onclick handler

javascripthtmlonclick

提问by user623879

Lets say I have a form as below. How do I pass the value in the textbox named "configname" to the onclick function handler??

假设我有一个如下表格。如何将名为“configname”的文本框中的值传递给 onclick 函数处理程序?

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(configname)" />
    </form>

回答by Sarfraz

Give an idto input field:

给一个id输入字段:

<input type="text" id="configname" name="configname" />

Now modify click handler as follows:

现在修改点击处理程序如下:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.getElementById('configname').value)" />

Or if you have only one form on that page, you could also use formsarray:

或者,如果该页面上只有一个表单,您也可以使用forms数组:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.forms[0].configname.value)" />

回答by Andrew D.

<form id="loadconfigform">
   Config Name: <input type="text" id="configname" name="configname" />
   <input type="button" value="Submit"
     onclick="onLoadConfigPress(document.getElementById('configname').value);" />
</form>

回答by Some Guy

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(document.getElementsByName('configname')[0].value)" />
    </form>

Simply call it using its name. I'd recommend using ID though.

只需使用它的名字来称呼它。不过我建议使用ID。

This won't work if you have other elements with the same name, so do use ID like the other answers have suggested.

如果您有其他同名元素,这将不起作用,因此请像其他答案建议的那样使用 ID。