user623879
user623879

Reputation: 4142

javascript passing text input to a onclick handler

Lets say I have a form as below. How do I pass the value in the textbox named "configname" to the onclick function handler??

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(configname)" />
    </form>

Upvotes: 26

Views: 92045

Answers (4)

jomofrodo
jomofrodo

Reputation: 1149

This is an old, old question - but somehow I ended up here.

So, the magic word 'this' is your friend here. 'this' is the element that is clicked on, which will include the value of the element. So

<form id="loadconfigform">
    Config Name: <input type="text" name="configname" />
    <input type="button" value="Submit" onclick="onLoadConfigPress(this)" />
</form>

function onLoadConfigPress(el){

    var configName = el.value;
    // do other things
    // . . .
}

Side note: if you want to pass the original event along with 'this', include it as the first parameter as the magic word 'event'.

onclick="onLoadConfigPress(event,this)

Upvotes: 2

Some Guy
Some Guy

Reputation: 16210

<form id="loadconfigform">
        Config Name: <input type="text" name="configname" />
        <input type="button" value="Submit" onclick="onLoadConfigPress(document.getElementsByName('configname')[0].value)" />
    </form>

Simply call it using its name. I'd recommend using ID though.

This won't work if you have other elements with the same name, so do use ID like the other answers have suggested.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

Give an id to input field:

<input type="text" id="configname" name="configname" />

Now modify click handler as follows:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.getElementById('configname').value)" />

Or if you have only one form on that page, you could also use forms array:

<input type="button" value="Submit" 
  onclick="onLoadConfigPress(document.forms[0].configname.value)" />

Upvotes: 40

Andrew D.
Andrew D.

Reputation: 8230

<form id="loadconfigform">
   Config Name: <input type="text" id="configname" name="configname" />
   <input type="button" value="Submit"
     onclick="onLoadConfigPress(document.getElementById('configname').value);" />
</form>

Upvotes: 3

Related Questions