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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thelouvre
    New Member
    • Feb 2010
    • 12

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

    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.getEle mentById("LastN ameRow").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.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    impossible to say without knowing the code.

    Comment

    • rbuczynski
      New Member
      • Mar 2010
      • 10

      #3
      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:

      Code:
      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:

      Code:
      <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.

      Comment

      Working...