Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 910
user623879 Avatar asked Sep 15 '11 07:09

user623879


People also ask

Can I use onclick in input tag?

Description. The onclick property of an Input object specifies an event handler function that is invoked when the user clicks on the input element. It is not invoked when the click( ) method is called for the element. Only form elements that are buttons invoke the onclick event handler.

Is it bad to use onclick attribute?

It's a new paradigm called "Unobtrusive JavaScript". The current "web standard" says to separate functionality and presentation. It's not really a "bad practice", it's just that most new standards want you to use event listeners instead of in-lining JavaScript.

How Onclick works in JavaScript?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.


3 Answers

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)" /> 
like image 79
Sarfraz Avatar answered Oct 21 '22 20:10

Sarfraz


<form id="loadconfigform">
   Config Name: <input type="text" id="configname" name="configname" />
   <input type="button" value="Submit"
     onclick="onLoadConfigPress(document.getElementById('configname').value);" />
</form>
like image 40
Andrew D. Avatar answered Oct 21 '22 18:10

Andrew D.


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

like image 34
Some Guy Avatar answered Oct 21 '22 18:10

Some Guy