Omid
Omid

Reputation: 113

Reset checkbox to initial status

As you may know, Reset buttons in a form can not reset checkboxes to their initial status. How can I make that happen either with javascript or PHP or jquery or ...?
Here is the code I have:

<form method="POST">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset"> Reset </button>
<button type="submit"> Submit </button>
</form>

Upvotes: 4

Views: 17866

Answers (3)

apflieger
apflieger

Reputation: 1231

You can simply reset the checked state based on the html attribute

checkbox.checked = !!checkbox.attributes.getNamedItem("checked")

Upvotes: 0

Mahesh Singh Chouhan
Mahesh Singh Chouhan

Reputation: 2588

Try this:

var resetForm = function(){
    $('#form')[0].reset();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form method="POST" id="form">
<input type="text" name="name" id="name" value="default value" required >
<input type="checkbox" name="group[]" id="checkbox1" value="0" checked>
<input type="checkbox" name="group[]" id="checkbox2" value="1" >
<button type="reset" onclick="resetForm()"> Reset </button>
<button type="submit"> Submit </button>
</form>

Upvotes: 1

Virk Bilal
Virk Bilal

Reputation: 660

Iterate over all your input elements and uncheck the ones which are checked.

var allInputs = $( ":input" );

for(var i = 0; i < allInputs.length; i++) {

   if( $( 'input[type="checkbox"]:checked' ) )
      $( this ).prop('checked', false);
}

Or as James pointed out, this could be done in one line like this:

$( 'input[type="checkbox"]' ).prop('checked', false);

Upvotes: 6

Related Questions