There is a test where questions open one by one and I need to, that if the user has not chosen a single answer, then bring him a warning. I only work for the first question, and then no. help me please

Demo

var answercount; $("#flip").click(function() { $("#panel").show("slow"); }); $(".send").click(function() { if($('input:radio:checked').prop("checked")){ answercount = $(this).closest(".question").attr("id").split('-')[1]; console.log(answercount); $('#question-' + answercount).addClass('hidden'); answercount = answercount * 1 + 1; console.log(answercount); $('#question-' + answercount).toggleClass('hidden'); } else{ alert('mistake'); } }); 
 #panel { display: none; } .show { display: block; } .hidden { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a id="flip" href="#here">Начать тестирование</a> <div id="panel"> <div class="question show" id="question-1"> <h3>Выберите цитату, которая бы лучшим образом описывала ваше отношение к работе…</h3> <label> <input type="checkbox" name="sport">1. Все, что делаешь, надо делать хорошо, даже если совершаешь безумство. Оноре де Бальзак</label> <br> <label> <input type="checkbox" name="sport">2. Работай с умом, а не до ночи. Луций Анней Сенека</label> <br> <label> <input type="checkbox" name="sport">3. Работа отгоняет от нас три великих зла: скуку, порок и нужду. Вольтер</label> <br> <label> <input type="checkbox">4. Мне всегда лучше работается после того, как я послушаю музыку. Иоганн Вольфганг фон Гёте</label> <br> <label> <input type="checkbox">5. Ничего особенно не трудно, если разделить работу на небольшие части. Генри Форд</label> <br> <label> <input type="checkbox">6. Нет никчемной работы, а есть никчемные люди, которых не устроит никакая работа. Айн Рэнд. Атлант расправил плечи</label> <br> <label> <input type="checkbox">7. Самая сильная мотивация - это работать, чтоб потом не работать. Соцсети</label> <br> <p> <input class="send" type="submit" value="Отправить"> </p> </div> <div class="question hidden" id="question-2"> <h3>Вам принесли газету. Какие новости вы пропустите и не станете читать?</h3> <label> <input type="checkbox">1. Новости эстрады и звезд</label> <br> <label> <input type="checkbox">2. Финансовые и валютные котировки, бензин, погода</label> <br> <label> <input type="checkbox">3. Новости в политике и обществе</label> <br> <label> <input type="checkbox">4. Новости спорта</label> <br> <label> <input type="checkbox">5. Новости культуры</label> <br> <label> <input type="checkbox">6. Происшествия</label> <br> <label> <input type="checkbox">7. Новости айти и технологий</label> <br> <p> <input class="send" type="submit" value="Отправить"> </p> </div> </div> 

  • instead of $(".send").click(function() { try writing $("input .send").click(function() { . - Dmitriy Kondratiuk
  • @DmitriyKondratiuk why submit? I have not heard that such UI elements are called "submit". - Nick Volynkin
  • The button is not part of the user interface <input class="send" type="submit" value="Отправить"> please enlighten. And the question was originally another was - Dmitriy Kondratiuk

2 answers 2

First of all , why do you look for radio inputs in the code if you have all the checkbox questions? That is, you need this:

 $('input:checkbox:checked') 

Secondly , only for the first question does the condition work for you because after it, the checked input lines ALREADY IS (you selected something in the first question), respectively, the condition goes according to a positive variant. Therefore, you need to additionally filter checkboxes.

I threw the most banal version - Demo on jsfiddle just in case

 var answercount = 1; function getCurrentQuestionElement(answercount) { return $('#question-' + answercount); } $("#flip").click(function() { $("#panel").show("slow"); }); $(".send").click(function() { var currentQuestionElement = getCurrentQuestionElement(answercount); var inputRadioCheckedInCurrentQuestion = currentQuestionElement.find('input:checkbox:checked'); var inputRadioCheckedInCurrentQuestionFirstProp = inputRadioCheckedInCurrentQuestion.prop("checked"); if (!!inputRadioCheckedInCurrentQuestionFirstProp) { answercount = $(this).closest(".question").attr("id").split('-')[1]; console.log(answercount); $('#question-' + answercount).addClass('hidden'); answercount = answercount * 1 + 1; console.log(answercount); $('#question-' + answercount).toggleClass('hidden'); } else { alert('mistake'); } }); 
 #panel { display: none; } .show { display: block; } .hidden { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a id="flip" href="#here">Начать тестирование</a> <div id="panel"> <div class="question show" id="question-1"> <h3>Выберите цитату, которая бы лучшим образом описывала ваше отношение к работе…</h3> <label> <input type="checkbox" name="sport">1. Все, что делаешь, надо делать хорошо, даже если совершаешь безумство. Оноре де Бальзак</label> <br> <label> <input type="checkbox" name="sport">2. Работай с умом, а не до ночи. Луций Анней Сенека</label> <br> <label> <input type="checkbox" name="sport">3. Работа отгоняет от нас три великих зла: скуку, порок и нужду. Вольтер</label> <br> <label> <input type="checkbox">4. Мне всегда лучше работается после того, как я послушаю музыку. Иоганн Вольфганг фон Гёте</label> <br> <label> <input type="checkbox">5. Ничего особенно не трудно, если разделить работу на небольшие части. Генри Форд</label> <br> <label> <input type="checkbox">6. Нет никчемной работы, а есть никчемные люди, которых не устроит никакая работа. Айн Рэнд. Атлант расправил плечи</label> <br> <label> <input type="checkbox">7. Самая сильная мотивация - это работать, чтоб потом не работать. Соцсети</label> <br> <p> <input class="send" type="submit" value="Отправить"> </p> </div> <div class="question hidden" id="question-2"> <h3>Вам принесли газету. Какие новости вы пропустите и не станете читать?</h3> <label> <input type="checkbox">1. Новости эстрады и звезд</label> <br> <label> <input type="checkbox">2. Финансовые и валютные котировки, бензин, погода</label> <br> <label> <input type="checkbox">3. Новости в политике и обществе</label> <br> <label> <input type="checkbox">4. Новости спорта</label> <br> <label> <input type="checkbox">5. Новости культуры</label> <br> <label> <input type="checkbox">6. Происшествия</label> <br> <label> <input type="checkbox">7. Новости айти и технологий</label> <br> <p> <input class="send" type="submit" value="Отправить"> </p> </div> </div> 

    Assign the same class or another identical property to the checkboxes from the same question. And for verification, use foreach on this class. For example:

     mistake=1; $( ".class1" ).each(function( index ) { if ($(this).prop('checked')==checked){ mistake=0; } } if (mistake==1){ alert('mistake'); }