0

I have a database-driven test that I want to modify so that users can't submit the results unless they've tried to answer all the questions. I can simply insert "required" in most of the questions, but that doesn't work with questions that have multiple checkboxes as answers.

Someone suggested the following fix:

$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.;
$QA = '<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'" id="q'.$QID.'-'.$Value.'" value="'.$Value.'" '. $required .'> '.$QA.'</label>';

However, it inserts "required" with EVERY checkbox, which means a user can't submit the results unless they select every answer. Does anyone know how to fix this?

Also, what does the comment "it would be better to check the key instead of the value" mean? I don't understand what he meant by "key."

  • So you want to check if one or multiple of the five (or so) checkboxes that belong to question 27 (or so) is/are checked? – WcPc Mar 06 '16 at 04:34
  • http://stackoverflow.com/questions/22238368/multiple-checkboxes-at-least-1-required for client side or you can just validate on server? – Vladimir Ramik Mar 06 '16 at 04:34
  • @ WcPC - I want to make sure a user checks at least ONE answer. Let's say there are five possible answers (A, B, C, D and E) and two correct answers (B and E). If the user selects the first answer (A), the submit button should work. In fact, it should work regardless of which answer or combination of answers is chosen. –  Mar 06 '16 at 04:45
  • @ Vladimir Ramink - I think that will work! The only problem is that if I choose an answer to a "standard question" (input type="radio"), it flashes a message that I need to choose a checkbox - even though I haven't reached the question with the checkboxes yet. But if I play around with my code, I might be able to fix that. –  Mar 06 '16 at 04:55

1 Answers1

0

There is no pure HTML way to do what you want.

You could use jQuery as shown in the linked answer or PHP validation but I guess you want to avoid the postback / page refresh.

About the key vs value: The key might be the question itself while the value is only one of the possible answers. So the comment might mean "You should make the question required, not the answers", but I'm just guessing here.

You could add a "required" field to your database and based on that value decide on the frontend if the question should be required or not, especially if you plan to build in non-required questions aswell.

Community
  • 1
  • 1
WcPc
  • 457
  • 2
  • 11