A+ A-

Onclick event in javascript

Input (User Input) :

Clicks are powerful and easy and you can add an onClick event to pretty much any HTML element, but sometimes you need to be able to ask for input from the user and process it. For that you'll need a basic form element and a button.

 [code type="JavaScript"]
<input id='userInput' size=60>
<button onClick='userSubmit()'>Submit</button>
<BR>
<P><div id='result'></div>
[/code]


Here we create an input field and give it a name of userInput. Then we create a HTML button with an onClick event that will call the function userSubmit(). These are all standard HTML form elements but they're not bound by a <form> tag since we're not going to be submitting this information to a server. Instead, when the user clicks the submit button, the onClick event will call the userSubmit() function.

[code type="JavaScript"]
<script type='text/javascript'>
function userSubmit() {
var UI=document.getElementById('userInput').value;
document.getElementById('result').innerHTML='You typed: '+UI;
}
</script>
[/code]


Here we create a variable called UI which looks up the input field userInput. This lookup is exactly the same as when we looked up our feedback division in the previous example. Since the input field has data, we ask for its value and place that value in our UI variable. The next line looks up the result division and puts our output there. In this case the output will be "You Typed: " followed by whatever the user had typed into the input field.

We don't actually need to have a submit button. If you'd like to process the user input as the user types then simply attach an onKeyup event to the input field as such

[code type="JavaScript"]
<input id='userInput' onKeyUp="userSubmit()" size=60>
<BR>
<P><div id='result'></div>
[/code]

There's no need to modify the userSubmit() function. Now whenever a user presses a key while the userInput box has the focus, for each keypress, userSubmit() will be called, the value of the input box retrieved, and the result division updated.

Clicks are powerful and easy and you can add an onClick event to pretty much any HTML element, but sometimes you need to be able to ask for input from the user and process it. For that you'll need a basic form element and a button.