Search code examples
javascripthtmlcheckboxdeselect

JavaScript- Clear the value of a checkbox in a hidden section of HTML


I have a web form displaying a number of questions. It was recently reported that one of the questions shown in a conditional section of the form was retaining its value when the condition used to display that question was met, then not met, and met again.

i.e. If the user answered 'Yes' to question 1, questions 1a & 1b would be shown, if they changed their answer to question 1 to 'No', questions 1a & 1b would be hidden, but if they changed their answer to question 1 back to 'Yes', questions 1a & 1b would be shown again with the answers previously given still selected. 1a & 1b should return to blank/ null values once they were hidden & shown again.

I managed to blank the answers to parts (a) & (b) when hidden and re-shown if (a) & (b) are drop down form elements with the following code:

However, the form consists of fields of a number of different types, and I'm currently having a bit of trouble getting it to clear the selected options for a list of checkboxes (where selection of multiple checkboxes is possible).

I tried to clear the selection in a similar way to how I had done for the dropdown:

var cb = hiddenwrapper.children('select[id^="checkbox"]');
cb.checked = false;

However, when I hide & re-show the question with the checkbox answers by selecting 'Yes' & 'No' as the answer to question 1, the previously checked checkboxes are still checked when the question is re-shown.

The debug I've added to show the value of cb.checked after setting it to false does show that it's value is false, but the checkboxes themselves are actually still checked:

cb:

checked: false

length: 0

How can I clear the selected checkboxes when the question is hidden & re-shown?


Solution

  • The correct way to check/uncheck checkboxes using jQuery is the .prop() method.

    http://api.jquery.com/prop/

    So it should be something like this:

    var cb = hiddenwrapper.children('select[id^="checkbox"]');
    cb.prop('checked', false);