Have you checked to ensure that an ID attribute is assigned to the text field element? Sometimes coders confuse NAME and ID attributes or forget one or the other. A simple but common mistake.
Another way to clear text field data with the click of a button is to write a function that loops through all fields in a given form, tests them for field type and clears their values accordingly.
Here's a sample:
- function clearTextFields(oForm) {
-
for(var i=0;i<oForm.elements.length;i++) {
-
if(oForm.elements[i].type=='text')
-
oForm.elements[i].value='';
-
}
-
}
Bind this function to the onClick event of your buttons.
A complete working demonstration using inline event handling:
- <script>
-
function clearTextFields(oForm) {
-
for(var i=0;i<oForm.elements.length;i++) {
-
if(oForm.elements[i].type=='text')
-
oForm.elements[i].value='';
-
}
-
}
-
</script>
-
<form>
-
<input type="text" id="field1" value="test" />
-
<input type="text" id="field2" />
-
<input type="button" value="Clear" onClick="clearTextFields(this.form);">
-
</form>
If you use
inline event handling then you can pass a reference to the form easily, as long as the button is an input element and contained within the target form.
Otherwise, if you bind using the
traditional or
advanced models then you'll have to trace the event to find the target form or else hard-code a fixed reference to a form.