views:

3403

answers:

5

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>
A: 

document.getElementById('textbox1').value

erikkallen
The textbox doesn't have an id.
karim79
Of course, you'd need to make textbox1 the element's id.
Chuck
+1  A: 

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

peirix
A: 

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;
David Robbins
It is `getElementsByName` (plural).
Gumbo
Yikes - fixed it.
David Robbins
Why this post was downvoted????
rahul
+2  A: 

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" />
Gumbo
A: 

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

natch3z