JavaScript Handling Events in Asp.Net

Event

Raised when

HTML tags

onfocus

Form field gets focus

select, text, textarea

onblur

Form field looses focus

select, text, textarea

onchange

Content of a field changes

select, text, textarea

onselect

Text is selected

text, textarea

onmouseover

Mouse moves over a link

A

onmouseout

Mouse moves out of a link

A

onclick

Mouse clicks an object

A, button, checkbox, radio, reset, submit

onload

Page is finished loading

body, frameset

onunload

Browser opens new document

body, frameset

onSubmit

Submit button is clicked

form

Example: Handling an event

 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>General Examples</title>
<script language=”JavaScript” type=”text/JavaScript”>
function SayHello() {
window.alert(“Hello ” +
document.forms[0].txtName.value);
}
</script>
</head>
<body>
<form name=”form1″>
Name: <input type=”text” name=”txtName” />
<input type=”button” value=”Say Hello” onclick=”JavaScript:SayHello()” />
</form>
</body>
</html>

Using Dropdown List (Select tag):

Example: DropdownList
 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>General Examples</title>
<script type=”text/JavaScript”>
function Calculate() {
var n1 = document.form1.txtN1.value;
var n2 = document.form1.txtN2.value;
var ddl = document.form1.selOperation
var opt = ddl.options[ddl.selectedIndex]; //returns selected option
switch (opt.value) {
case “+”:
document.form1.txtResult.value = parseInt(n1) + parseInt(n2);
break;
case “-“:
document.form1.txtResult.value = n1 – n2;
break;
case “*”:
document.form1.txtResult.value = n1 * n2;
break;
case “/”:
document.form1.txtResult.value = n1 / n2;
break;
}
}
</script>
</head>
body>
<form name=”form1″>
<input type=”text” name=”txtN1″ />
<select name=”selOperation” onchange=”Calculate()”>
<option value=”+”>+</option>
<option value=”-“>-</option>
<option value=”*”>*</option>
<option value=”/”>/</option>
</select>
<input type=”text” name=”txtN2″ />
=
<input type=”text” name=”txtResult” readonly=”readonly” />
</form>
</body>
</html>

Leave a Reply