[javascript] 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>

This question is related to javascript html

The answer is


As opposed to passing the text as a variable, you can use the DOM to retrieve the data in your function:

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

if I have understood correct the question :

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


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>

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


document.getElementById('textbox1').value


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. :)