Home > Enterprise >  Jquery form reset function doesn't reset checkboxes
Jquery form reset function doesn't reset checkboxes

Time:11-30

I have a form that contains checkboxes, and from the script I check and uncheck them according to some requirements. at a certain point I reset the form $("#formId")[0].reset(), all inputs get reseted exept for checkboxes!!

I reseted the form but checkboxes didn't get reseted.

CodePudding user response:

<form id="cityForm" name= "input" action="#" method="get">
    <input type="text" name="cityName"><br>
    <input type="checkbox" id="city_1" name="city_1" value="New York">
    <label for="city_1"> New York</label><br>
    <input type="checkbox" id="city_2" name="city_2" value="Alaska">
    <label for="city_2"> Alaska</label><br>
    <input type="checkbox" id="city_3" name="city_3" value="California">
    <label for="city_3"> California</label><br>
    <input type="submit" id="citysubmit" value="Submit">
    <input type="reset" id="cityreset" value="Reset">
</form>

<script type="text/javascript">
    $('#cityreset').click(function(){
        $('#cityForm')[0].reset();
    });
</script>

Please check my code and let me know if you find any issue

CodePudding user response:

  • It turns out cuz I was using attr('checked', true) I switched to prop('checked', true) and it worked.
  • After some debugging I found that attr() adds an attribute checked to the input (checked="checked") while prop() doesn't add anything. I also found that prop() is newer and was released in version 1.6, while attr() in version 1.0

So I advice you to use prop() more often than attr()

  • Related