1

I've created a database-driven test with three types of questions - input type = radio, text and checkbox. If I insert required before the closing tag, it works fine for the radio and text questions, but not the checkboxes.

The problem is that each checkbox question has several possible answers - anywhere from three to six. And the number of those choices that are correct answers also varies.

But when I add "required" to the checkbox script, the user has to select EVERY answer in order to proceed to the results page. This is what the code looks like:

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

I found the HTML5 Required Attribute page, which appears to address this problem. If I understand correctly, you can fix the problem by inserting "required" in just one element. So if you insert it in answer A, a user could presumably choose answers C and D, and everything would work just fine.

If that's correct, then is there a way to make "required" display in just one checkbox, instead of all of them?

Community
  • 1
  • 1
  • Why dont you use 'required' only in then first checkbox of a group using a condition written in php? – SachinSunny Mar 05 '16 at 03:48
  • Good tip; can anyone show me how to do that? For example, is there a way to write a PHP switch that says that says 1) insert "required" only in answers where input type = checkbox ("required" is already inserted in the other input types), and 2) insert "required" in just the FIRST checkbox of each group? –  Mar 05 '16 at 04:01

1 Answers1

1

Use required using a condition for the first checkbox of a group. I assume your html code is written in .php files.

$required = ($Value == 0) ? "required" : ""; //condition to check if the value is first. since it is database driven it would be better to check the key instead of the value.;
   echo '<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'[]" id="q'.$QID.'-'.$Value.'" value="'.$Value.'" '. $required .'> '.$QA.'</label>';

Another solution is to add required attribute using Jquery. For eg if gender is the name of the group of checkboxes, then:

$('input[type=checkbox][name=gender]')[0].attr('required', 'required');;
SachinSunny
  • 1,681
  • 1
  • 12
  • 20