E
E
Ekaterina Mikhailova2019-04-09 17:45:51
Vue.js
Ekaterina Mikhailova, 2019-04-09 17:45:51

How to check selected checkbox in vue.js?

I create a test questionnaire on vue.js, the questionnaire consists of slides, I chose the option on the first slide, click next, there are new options, it is necessary that if no checkbox is selected, the button will not work further.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://vuejs.org/js/vue.js"></script>
    <title>Опрос</title>
  </head>
  <body>
    <div id="app">
      <div class="container">
        <!-- index is used to check with current question index -->
        <div class="first_screen" v-show="questionIndex === 0">
          <h1>Пройди опрос</h1>
          <div class="pink_text">Это займет 1-2 минуты</div>
          
                <button class="btn-pink_bg mr-3" v-on:click="next_first">
                  Пройти опрос
                </button>
        </div>
        <div class="screen" v-for="(question, index) in quiz.questions" :class="'screen_' + question.id">
          <transition 
                      v-on:before-enter="beforeEnter"
                      v-on:enter="enter"
                      v-bind:css="false"
                      >
            <div v-show="index+1 === questionIndex">
              <h2>{{ question.text }}</h2>
              <ol>
                <li v-for="response in question.responses" :class="question.id" >
                  <label :class="question.pswdType">
                    <input v-if="questionIndex < 3" type="radio"
                           :value="response.text"
                           :name="index" 
                           v-model="pickeds"> 
                    <input v-else type="checkbox"
                           :value="response.text"
                           :name="index" 
                           v-model="checkedNames"> 
                    <div :class="question.pswdType + '__text'">{{response.text}}</div> 
                  </label>
                </li>
              </ol>
              <div class="text-center">
                <button class="btn-prev" v-if="questionIndex > 0" v-on:click="prev">
                  Назад
                </button>
                <button class="btn-pink_bg" v-on:click="next">
                  Далее
                </button>
              </div>
            </div>
          </transition>
        </div>
        <div v-show="questionIndex === quiz.questions.length+1">
          <h2>
            Опрос успешно завершен
          </h2>
          <p>
            Отмеченные поля: 
          </p> 
          <ul >

            <li v-for="checkedName in checkedNames">
              {{ checkedName }}
            </li>
          </ul>
        </div>
      </div>
    </div>



    <script>
      let quiz = {
        questions: [
          {
            text: "тут выбираем только один ответ",
            pswdType: 'radio', 
            id: 'type_site',
            responses: [
              {text: 'первый '}, 
              {text: 'второй'}, 
              {text: 'третий'}, 
              {text: 'четвертый'},
            ]
          } , {
            text: "тут  ТОЖЕ выбираем только один ответ",
            pswdType: 'radio',
            id: 'design',
            responses: [
              {text: 'Уникальный'}, 
              {text: 'Шаблонный'}, 
              {text: 'Рассчитать оба варианта'}, 
            ]
          }
          , {
            text: "Здесь множественный выбор",
            pswdType: 'checkbox',
            id: 'cart_product',
            responses: [ 
              {text: 'Выбор цвета'}, 
              {text: 'Рекомендации'}, 
              {text: 'Выбор размера'}, 
              {text: 'Выбрать ширину'}, 
            ]
          }
          , {
            text: "И здесь множественный выбор",
            pswdType: 'checkbox',
            id: 'list_product',
            responses: [
              {text: 'Вес'}, 
              {text: 'Рост'},
              {text: 'Ширина'}, 
              {text: 'Глубина'},  
            ]
          }
        ]
      };

      new Vue({
        el: '#app',
        data: {
          quiz: quiz,
          questionIndex: 0,
          pickeds: [],
          checkedNames: [],
        },

        methods: {

          next_first: function() {
            this.questionIndex++;
            this.updateHistory();
          },
          next: function(index) {
            if((this.checkedNames.length!==0) || (this.pickeds.length!==0)){
              this.questionIndex++;
              this.updateHistory();
            }
          },

          prev: function() {
              this.questionIndex--;
              this.updateHistory();
          },

          updateHistory: function() {
            history.pushState({questionIndex: this.questionIndex}, "Question " + this.questionIndex);
          }

        }
      });
    </script>
  </body>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-04-09
@katyamishha

Create an array called answers to hold the answers. Depending on the number of expected responses (one or more), its elements will be strings or arrays.
Associate answers elements with answer options radio buttons/checkboxes:
v-model="answers[questionIndex]"
Create a computed property that will be an indicator of the answer/answers to the current question:

computed: {
  answerSelected() {
    return this.answers[this.questionIndex].length;
  },
},

And finally use this property to disable the next question button:
:disabled="!answerSelected"
UPD. https://jsfiddle.net/20L61r85/UPD
. Taken from the comments:
And can you tell me how to display not only the checked fields in the result, but to what question were these fields marked?

You can add an index in the template when sorting through the answers , by which we will get the question. Or you can make the answer a property of the question - then when displaying the results, we sort through the questions, and all the necessary information is available in one place.

D
Dmitry Gololobov, 2019-04-09
@dGololobov

Try on the add button

<button  class="btn-pink_bg" v-on:click="next" v-bind:disabled="!checked[0]">Далее </button>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question