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>
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.
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.
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.
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)" />
<form id="loadconfigform">
Config Name: <input type="text" id="configname" name="configname" />
<input type="button" value="Submit"
onclick="onLoadConfigPress(document.getElementById('configname').value);" />
</form>
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With