Joy
Joy

Reputation: 4463

Resetting the fields of form by Javascript

I have a drodown box in my html form. I want when "0" is selected from the dropdown then the form should be reset otherwise make the ajax call to fill the form. I have written the following code for that purpose, but it is not working, I mean the form fields are not being reset.

$("select#student_id").change(function(){
  var student = $(this).val;
  if(student!=0)
    {
      //Here I make the ajax call to populate the form
    }

Here how can I reset the form fields.

Upvotes: 0

Views: 115

Answers (5)

zkanoca
zkanoca

Reputation: 9918

$("select#student_id").change(function(){
  var student = $(this).val;
  if(student!=0)
    {
      //Here I make the ajax call to populate the form
    }
  else
  {
    var $form = $('#form_id_here');
    $form.find("input, textarea, hidden").val("").text("");
    $form.find("input[type='checkbox'], input[type='radio']").is(":checked").attr('checked', false);
  }
});

Upvotes: 1

Lucian Preda
Lucian Preda

Reputation: 13

$( "#student_id" ).change(function(event, ui){
    if( $(this).val() != 0 )
    {
      //Here I make the ajax call to populate the form
      alert("Fill the form");
    }
    else {
        //reset all the fields of the form to the default values
        $(event.target.form)[0].reset();
    }
});

Upvotes: 0

Igor Goldny
Igor Goldny

Reputation: 50

its not working for you because reset is not a jquery function you need to call reset function on the dom element

$('form')[0].reset()

Upvotes: 1

lrente
lrente

Reputation: 1130

You have to say what happens when the user selects '0'.

if(student!=0)
    {
      //Here I make the ajax call to populate the form
}
else{
 //reset form
}

Upvotes: 0

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

$("select#student_id").change(function(){
    var student = $(this).val();
    if(student!=0) {
        //make ajax call
    } else {
        $("form").reset();
    }
});

Upvotes: 1

Related Questions