How to pass text in a textbox to JavaScript function?

0 votes
asked Apr 19, 2009 by natch3z

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>

6 Answers

0 votes
answered Jan 19, 2009 by erikkallen

document.getElementById('textbox1').value

0 votes
answered Jan 19, 2009 by natch3z

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

0 votes
answered Apr 19, 2009 by peirix

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

0 votes
answered Apr 19, 2009 by david-robbins

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;
0 votes
answered Apr 19, 2009 by gumbo

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" />
0 votes
answered Sep 15, 2017 by ayaat-shifa

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>
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...