samedi 5 mars 2016

Checkbox: jQuery required function

This is the code I'm using to display questions where users are required to select one or more checkboxes as answers:

$QA = '<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'[]" id="q'.$QID.'-'.$Value.'" value="'.$Value.'"> '.$QA.'</label>';

And here's a typical display:

<li id="q8">
  <div class="Question">Which ones are countries?</div>
  <div class="Answer">
    <label for="q6-A"><input type="checkbox" name="q6[]" id="q6-A" value="A"> Texas</label>
    <label for="q6-B"><input type="checkbox" name="q6[]" id="q6-B" value="B"> Japan</label>
    <label for="q6-C"><input type="checkbox" name="q6[]" id="q6-C" value="C"> Spain</label>
  </div>
</li>

I want to modify the code so that the form won't submit unless a user selects at least one checkbox. Every script I've tried requires them to choose EVERY checkbox, but I just want to make sure they attempt to answer the question by choosing ANY ONE checkbox.

Someone suggested the following script:

$('input[type=checkbox][name=gender]')[0].attr('required', 'required');;

So I replaced "name=gender" with "name=q6[]", but that doesn't work. I'm guessing the brackets after q6 might be a problem, but if I remove the brackets from the code that drives the form - name="q'.$QID.'[]" - then the test is scored incorrectly on the results page.

Another problem is that this script requires a specific name, when similar multiple-choice checkbox questions on various tests can have various names.

Is there some way to modify this script so that it targets ALL questions that have checkboxes, requiring users to select at least one checkbox?




Aucun commentaire:

Enregistrer un commentaire