如何将 html 文本框值传递给 javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7107398/
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
How to pass html textbox value to a javascript function
提问by Tanu
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:
我有一个 HTML 文本框,用户将在其中输入一些我想传递给 JavaScript 函数的字符串:
<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
onClick="ADSEARCHGF.showTable('');"/>
Please suggest how can i do it.
请建议我该怎么做。
回答by StuperUser
If the event is raised by the button, you will not have the text input object to pass to the function without getting it first, getting it by id is the best way.
如果事件是由按钮引发的,那么在没有先获取的情况下,您将无法将文本输入对象传递给函数,通过 id 获取它是最好的方法。
You can use the id of the text box:
您可以使用文本框的 id:
var searchValue = document.getElementById('ad_search_query').value;
in your function, or use Ahsan Rathod's method to use this code as parameter.
在您的函数中,或使用 Ahsan Rathod 的方法将此代码用作参数。
回答by fatnjazzy
<script>
function showTable(obj){
alert(obj.value)
}
</script>
<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query'));"/>
回答by Ahsan Rathod
Do this:
做这个:
JS:
JS:
<script>
function showTable(val) {alert(val);}</script>
<script>
函数 showTable(val) {alert(val);}</script>
HTML:
HTML:
<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query').value);"/>
See this Demo: http://jsfiddle.net/rathoreahsan/8ddbD/
回答by Arun Rana
In javascript function you can access textbox value like this
在javascript函数中,您可以像这样访问文本框值
var text = document.getElementsByName("textbox1").value;
var text = document.getElementsByName("textbox1").value;