dev_py_uk
dev_py_uk

Reputation: 428

Make a checkbox unchecked when it is hidden using JavaScript

I have a JavaScript function in place for a multiple choice quiz:

If the answer is 'Yes' - (checked by a checkbox) - Then a sub-question will appear, but if the user clicks 'No' the sub-question won't appear.

JavaScript

   $(document).ready(function() {
  var par = $('#SQ1');
  $(par).hide();

  $('#Q1').click(function(e) {
      $(par).slideToggle('slow');

  });
});

    $(document).ready(function(){
      $('#Q1NO').click(function(){
         $('#SQ1').hide('slow');
      });
   })

Questions checkboxes

<div>
    <input type="checkbox" id="Q1" name="chk[]" value="Yes">&nbsp;Yes</input>
<br>
    <input type="checkbox" id="Q1NO" name="chk[]" value="No">&nbsp;No</input>
</div>

Sub-Question checkboxes

  <div id="SQ1">
<div>
    <input type="checkbox" name="chk[]" value="Yes 2" id="Q1R">&nbsp;Yes</input>
<br>
    <input type="checkbox" name="chk[]" value="No 2">&nbsp;No</input>
</div>
</div>

I am inputting the values from the checkboxes into a database and the problem is that if the user clicked 'Yes' and then selected a box from the sub-question, but then changed their mind and clicked 'No' on the primary question, the sub-question will disappear, but the box is still checked inside it and it gets added to the database - Which I don't want.

Is there a way to uncheck an item within a div, on the click of the 'No' from the first div?

Thanks for reading

Upvotes: 1

Views: 2951

Answers (3)

Roger Barreto
Roger Barreto

Reputation: 2284

Uncheck all subquestions checkboxes:

$('#Q1NO').click(function(){
     $('#SQ1').hide('slow')
     .find('input:checkbox').prop('checked',false);
});

Upvotes: 2

gotomanners
gotomanners

Reputation: 7906

Solution without loop as you can set properties on all query matches.

 $('#Q1NO').click(function() {
    par.hide('slow');
    par.find("input[type=checkbox]").prop('checked', false);
  });

Upvotes: 1

Sam4Code
Sam4Code

Reputation: 551

First of all there either should be radio button for Yes/no or only one checkbox. There are several ways to achieve your requirement. I have posted below easiest one. See if it helps.

function showHideSub(isChecked){

if(isChecked)
{
$("#sub").show()
}
else
{
$("#sub").hide()
$("#sub input[type=checkbox]").removeAttr("checked");

}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>
    <input type="checkbox" id="Q1" name="chk[]" onclick="showHideSub(this.checked)" value="Yes">&nbsp;Yes / No </input>
<br>
   
</div>


<div id="sub" style="display:none">
    <input type="checkbox" name="chk[]" value="Yes 2" id="Q1R">&nbsp;Yes/No</input>

</div>

Upvotes: 2

Related Questions