Question

So I have a quiz-like form. It contains questions and answers. I need the form to have no radio checked on document ready. I achieved that with:

$(document).ready(function(){
 $('input[type="radio"]').prop('checked', false)
});

(as of the comment) Now I need the form to be submittable only if the user picks ONE answer FOR EACH question. If a question remains with NO answer checked, there should be an alert box and the form should not be submitted.

The form looks like this: jsFiddle of course, it is generated server side by PHP, but this is a sample of what it looks like after generation. Also, the java function I tried only checks for ONE radio of all radios of all questions. I need to check EACH question for checked radios

How can I achieve that?

Was it helpful?

Solution

I've made some modification to the jsfiddle http://jsfiddle.net/eVLhD/3/.

In the HTML code, I've wrapped each question inside a div: <div class="question"> </div>

Then in the submit function, I do: for each question, check if there is a checked option. If there is none, stop the submit, alert and stop the loop.

function atleast_onecheckbox(e) {
    var error = 0, i = 1;
    $('div.question').each(function() {
        if ($(this).find(':checked').length === 0) {
            e.preventDefault();
            alert('no way you submit it without checking a box in question ' + i);
            error++;
            return false;
        }
        i++;
    });
    return error === 0;
}      

OTHER TIPS

If the radio's are part of the same collection (per question) then it shouldn't be possible for the user to select more than one. Another thing, are the questions fixed or are they dynamic? I mean, do you always have the same number of questions, or can this amount vary?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top