简体   繁体   中英

How to pass text in a textbox to JavaScript function?

Suppose I have the following HTML code, how can I pass the user's input to execute(str) JavaScript function as an argument?

<body>

<input name="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(//send the user's input in textbox1 to this function//)" type="button" value="Execute" />

</body>

You could either access the element's value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById :

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

与将文本作为变量传递相反,您可以使用DOM来检索函数中的数据:

var text = document.getElementsByName("textbox1").value;

You could just get the input value in the onclick-event like so:

onclick="execute(document.getElementById('textbox1').value);"

You would of course have to add an id to your textbox

if I have understood correct the question :

 <!DOCTYPE HTML> <HEAD> <TITLE>Passing values</TITLE> <style> </style> </HEAD> Give a number :<input type="number" id="num"><br> <button onclick="MyFunction(num.value)">Press button...</button> <script> function MyFunction(num) { document.write("<h1>You gave "+num+"</h1>"); } </script> </BODY> </HTML> 

的document.getElementById( 'TextBox1的')。值

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

You can get textbox value and Id by the following simple example in dotNet programming

<html>
        <head>
         <script type="text/javascript">
             function GetTextboxId_Value(textBox) 
                 {
                 alert(textBox.value);    // To get Text Box Value(Text)
                 alert(textBox.id);      // To get Text Box Id like txtSearch
             }
         </script>     
        </head>
 <body>
 <input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" />  </body>
 </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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