The task is the following: to make a test, so that by pressing a button one question would appear, the user would select the necessary answers and click on answer, after that the first question should disappear and the second should appear and so on until the last question.

Actually, everything that I have I put in the example, gives the following error, I can not understand what is the matter:

VM123: 62 Uncaught TypeError: Cannot read property 'split' of undefined I really hope for your help!

Demo:

var answercount; $(document).ready(function() { $("#flip").click(function() { $("#panel").show("slow"); }); $(".send").click(function() { answercount = $(this).parent().attr('id').split('-')[1]; alert(answercount); $('#question-' + answercount).addClass('hidden'); answercount = answercount * 1 + 1; alert(answercount); $('#question-' + answercount).addClass('show'); }); }); 
 #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> <p> <input class="send" type="submit" value="Отправить"> </p> </div> <div class="question hidden" id="question-3"> <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> 

    1 answer 1

    $(this).parent().... In your cases, it tries to return the id paragraph in which the button lies (it is missing, therefore returns nothing).

    Either remove the paragraph or use closest () , for example:

     answercount = $(this).closest(".question").attr("id").split('-')[1]; 

    In this case, all parents will be reviewed for class question .

    Well, I think it's better to use toggleClass () to change the class of the next question.

    Example at work: (2 questions in the test)

     var answercount; $("#flip").click(function() { $("#panel").show("slow"); }); $(".send").click(function() { 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'); }); 
     #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> 

    • @Igorevich and if I have more than two questions in the test, 3 for example, then how much when I click on start testing, then two questions appear at once jsfiddle.net/alcheez/jh5e3otx/3 do not know why this could be - Alexander Syrokvasovsky
    • question-2 a show class. By default, set everything except the first one to hidden , and `toggleClass` will delete this class when answering the previous question. - Alexander Igorevich
    • @Igorevich Oh, damn, sure, thank you very much for your help! - Alexander Syrokvasovsky
    • @Igorevich and another, rather theoretical question, what is the easiest way to save the answer choices that the user chose (maybe several in each question), what would then, for example, display his answers for each question? - Alexander Syrokvasovsky
    • There are lots of options, depending on what you need to do with the data. For example, you can use localStorage or just start some kind of array and push answers into it. This is no longer relevant to this question, if you are interested, then ask a new question (first you tried to do something yourself) and you will be sure to tell you if something does not work out. - Alexander Igorevich