By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,702 Members | 1,760 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,702 IT Pros & Developers. It's quick & easy.

want a clear subroutine that only clears text fields, not my buttons

P: 12
i want to define a clear button that instead of resetting the entire form, only the text values are set to "". I tried with
document.getElementById("LastNameRow").value = "";
but when my program runs, i enter data into the last name field and then press clear and the data remains. what am i missing? I know that i am entering my clear routine on click because my alerts are printing.
Feb 25 '10 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,639
impossible to say without knowing the code.
Feb 26 '10 #2

P: 10
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:

Expand|Select|Wrap|Line Numbers
  1. function clearTextFields(oForm) {
  2.   for(var i=0;i<oForm.elements.length;i++) {
  3.     if(oForm.elements[i].type=='text')
  4.       oForm.elements[i].value='';
  5.   }
  6. }
Bind this function to the onClick event of your buttons.

A complete working demonstration using inline event handling:

Expand|Select|Wrap|Line Numbers
  1. <script>
  2. function clearTextFields(oForm) {
  3.   for(var i=0;i<oForm.elements.length;i++) {
  4.     if(oForm.elements[i].type=='text')
  5.       oForm.elements[i].value='';
  6.   }
  7. }
  8. </script>
  9. <form>
  10.   <input type="text" id="field1" value="test" />
  11.   <input type="text" id="field2" />
  12.   <input type="button" value="Clear" onClick="clearTextFields(this.form);">
  13. </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.
Mar 10 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.