I have a simple web form with Name, email and subject. In the fields I have the values set to examples, like <input id=name value=‘John Smith’>
What is the simplest way to have jQuery clear the field when I user clicks in the field, and then put the sample text back if the user does not enter anything in the field?
system
November 26, 2010, 11:06pm
2
Does it have to be done in jquery?
If not, then maybe something similar to this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var inpValues = new Array();
inpValues['txtName'] = 'John Smith';
inpValues['txtSubject'] = 'Rocket Science';
function setDefValue(elem) {
if(inpValues[elem.id]) {
elem.value = inpValues[elem.id];
}
}
window.onload=function() {
var formElemsA = document.getElementById("frm_1").getElementsByTagName('input');
for(var i=0; i < formElemsA.length; i++) {
//assign a default value
setDefValue(formElemsA[i]);
//assign onblur event handler
formElemsA[i].onblur=function() {
if(this.value == '') {
setDefValue(this);
}
}
//assign onclick event handler
formElemsA[i].onclick=function() {
this.value = '';
}
}
}
</script>
</head>
<body>
<form id="frm_1" action="" method="post" />
Name <input type="text" id="txtName" name="txtName" />
Subject <input type="text" id="txtSubject" name="txtSubject" />
</form
</body>
</html>