How to clear all input fields in a specific div with jQuery?

Jquery

Jquery Problem Overview


I am trying to use jQuery to do a simple thing: clear the input fields of a group of input field within a div whenever the form loads, or if the user changes a picklist; but I'm having a devil of a time getting the selector to work.

First, here's my onclick and onload triggers:

<form name="EditGenotype" action="process_GenotypeMaint.php" method="POST" onsubmit="return false" onload=clear_fetch() >

and on the picklists:

<SELECT multiple size=6 NAME="marker" onchange=show_marker() onclick=clear_fetch() >

Next, here's my HTML input elements in the div I want to clear:

  <div class=fetch_results>
      <fieldset>
	<LEGEND><b>Edit Genotype, call 1</b></LEGEND>
	  <boldlabel>Allele_1</boldlabel><input id=allele_1_1 name=allele_1_1 size=5 >
	  <boldlabel>Allele_2</boldlabel><input id=allele_1_2 name=allele_1_2 size=5 >
	  <boldlabel>Run date</boldlabel><input id=run_date1 name=run_date1 size=10 disabled=true>
      </fieldset>
      <fieldset>
	<LEGEND><b>Edit Genotype, call 2</b></LEGEND>
	  <boldlabel>Allele_1</boldlabel><input id=allele_2_1 name=allele_2_1 size=5 >
	  <boldlabel>Allele_2</boldlabel><input id=allele_2_2 name=allele_2_2 size=5 >
	  <boldlabel>Run date</boldlabel><input id=run_date2 name=run_date2 size=10 disabled=true>
      </fieldset>
      <fieldset>
	<LEGEND><b>Edit Genotype, call 3</b></LEGEND>
	  <boldlabel>Allele_1</boldlabel><input id=allele_3_1 name=allele_3_1 size=5 >
	  <boldlabel>Allele_2</boldlabel><input id=allele_3_2 name=allele_3_2 size=5 >
	  <boldlabel>Run date</boldlabel><input id=run_date3 name=run_date3 size=10 disabled=true>
      </fieldset>
    </div>

Finally, here's my script:

 function clear_fetch() {    
    
    $('#fetch_results:input', $(this)).each(function(index) {
      this.value = "";
    })
    
  }

However, nothing happens...so, I must not have the selector correct. Does anybody see what I've done wrong?

Jquery Solutions


Solution 1 - Jquery

Fiddle: http://jsfiddle.net/simple/BdQvp/

You can do it like so:

I have added two buttons in the Fiddle to illustrate how you can insert or clear values in those input fields through buttons. You just capture the onClick event and call the function.

//Fires when the Document Loads, clears all input fields
$(document).ready(function() {
  $('.fetch_results').find('input:text').val('');    
});

//Custom Functions that you can call
function resetAllValues() {
  $('.fetch_results').find('input:text').val('');
}

function addSomeValues() {
  $('.fetch_results').find('input:text').val('Lala.');
}

Update:

Check out this great answer below by Beena as well for a more universal approach.

Solution 2 - Jquery

This function is used to clear all the elements in the form including radio button, check-box, select, multiple select, password, text, textarea, file.

function clear_form_elements(class_name) {
  jQuery("."+class_name).find(':input').each(function() {
    switch(this.type) {
        case 'password':
        case 'text':
        case 'textarea':
        case 'file':
        case 'select-one':
        case 'select-multiple':
        case 'date':
        case 'number':
        case 'tel':
        case 'email':
            jQuery(this).val('');
            break;
        case 'checkbox':
        case 'radio':
            this.checked = false;
            break;
    }
  });
}

Solution 3 - Jquery

Change this:

 <div class=fetch_results>

To this:

 <div id="fetch_results">

Then the following should work:

$("#fetch_results input").each(function() {
      this.value = "";
  })​

http://jsfiddle.net/NVqeR/

Solution 4 - Jquery

inspired from https://stackoverflow.com/a/10892768/2087666 but I use the selector instead of a class and prefer if over switch:

function clearAllInputs(selector) {
  $(selector).find(':input').each(function() {
    if(this.type == 'submit'){
		  //do nothing
	  }
	  else if(this.type == 'checkbox' || this.type == 'radio') {
    	this.checked = false;
      }
      else if(this.type == 'file'){
        var control = $(this);
        control.replaceWith( control = control.clone( true ) );
      }else{
        $(this).val('');
      }
   });
}

this should take care of almost all input inside any selector.

Solution 5 - Jquery

Couple issues that I see. fetch_results is a class, not an Id and the each function doesn't look right.

$('.fetch_results:input').each(function() {
      $(this).val('');
});

Just be sure to remember that if you end up with radios or check buttons, you will have to clear the checked attribute, not the value.

Solution 6 - Jquery

Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.

$('#divId').find(':input').val('');

Solution 7 - Jquery

Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!

let resetFormObject = (elementID)=> {
        document.getElementById(elementID).getElementsByTagName('input').forEach((input)=>{
            switch(input.type) {
                case 'password':
                case 'text':
                case 'textarea':
                case 'file':
                case 'select-one':
                case 'select-multiple':
                case 'date':
                case 'number':
                case 'tel':
                case 'email':
                    input.value = '';
                    break;
                case 'checkbox':
                case 'radio':
                    input.checked = false;
                    break;
            }
        }); 
    }

Solution 8 - Jquery

If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)

$("div.fetch_results input:text").each(function() {
  this.value = "testing";
})​

This will select only the text input boxes within the div with a fetch_results class.

As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.

Solution 9 - Jquery

$.each($('.fetch_results input'), function(idx, input){
  $(input).val('');
});

Solution 10 - Jquery

For some who wants to reset the form can also use type="reset" inside any form.

<form action="/action_page.php">
Email: <input type="text" name="email"><br>
Pin: <input type="text" name="pin" maxlength="4"><br>
<input type="reset" value="Reset">
<input type="submit" value="Submit">
</form>

Solution 11 - Jquery

Here is a simple one liner that worked for me

$('input','.container_class_name').val(null).trigger('change');

'input' being the elements you want to clear within the container, & 'container_class_name' being the container class or id name.

This works for all input's regardless of type (checkbox, radio, text), since the pointer is looking at the <input> element itself.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrixterView Question on Stackoverflow
Solution 1 - Jqueryuser1372494View Answer on Stackoverflow
Solution 2 - JqueryBeena ShettyView Answer on Stackoverflow
Solution 3 - JqueryMahnView Answer on Stackoverflow
Solution 4 - JqueryRemi MorinView Answer on Stackoverflow
Solution 5 - JquerykmfkView Answer on Stackoverflow
Solution 6 - JqueryTanner_GramView Answer on Stackoverflow
Solution 7 - JqueryNikolaos SeitzView Answer on Stackoverflow
Solution 8 - JqueryBrianMView Answer on Stackoverflow
Solution 9 - JqueryYumikoView Answer on Stackoverflow
Solution 10 - JqueryطلحةView Answer on Stackoverflow
Solution 11 - JquerytcanbolatView Answer on Stackoverflow