如何设置无线电元素的Check属性?

时间:2017-03-22 08:20:26

标签: javascript jquery html css

我正在尝试使用JavaScript和jQuery创建一个测验应用程序,如果我单击一个单选按钮我将一个属性设置为已选中但如果我转到另一个问题并单击上一个问题单元中的任何单选按钮按钮选择被删除即使我转到任何问题并选择那里的选项,我如何确保它被选中。我想它正在发生,因为我在单选按钮上有通用名称有人可以帮助我吗?

$(document).ready(function() {
  $(function() {
    var data = [{
        "id": 1,
        "question": "Which framework is best?",
        "options": ["ReactJs", "AngularJs", "Vue.js", "Backbone"],
        "correctanswer": "ReactJs",
        "selectedanswer": ""
      },
      {
        "id": 2,
        "question": "What does MVC stands for?",
        "options": ["Model View Controller", "Model view view Controller", "Model Controller view", "None of the above"],
        "correctanswer": "Model View Controller",
        "selectedanswer": ""
      },
      {
        "id": 3,
        "question": "Which is the best MOOC course website?",
        "options": ["Coursera", "EDX", "Udacity", "Code School"],
        "correctanswer": "Udacity",
        "selectedanswer": ""
      },
      {
        "id": 4,
        "question": "which backend framework is not available in any of the MOOC site?",
        "options": ["Ruby on Rails", "Node JS", "Metor Js", "Django"],
        "correctanswer": "Django",
        "selectedanswer": ""
      },
      {
        "id": 5,
        "question": "Which frontend framework is not available?",
        "options": ["AngularJs", "ReactJs", "Backbone", "Knockout"],
        "correctanswer": "ReactJs",
        "selectedanswer": ""
      }
    ];
    var constructordata = function(data) {
      this.id = data.id,
        this.question = data.question,
        this.options = data.options,
        this.correctanswer = data.correctanswer,
        this.selectedanswer = data.selectedanswer
    };
    var datas = [];
    data.forEach(function(item) {
      datas.push(new constructordata(item));
    });
    var controller = {
      nextquestion: function() {
        var currentelement = $('#app .questionsection.visible');
        var nextelement = currentelement.next();
        if (nextelement.hasClass('questionsection')) {
          currentelement.removeClass('visible');
          nextelement.addClass('visible');
        }
        if (!nextelement.next().hasClass('questionsection')) {
          $("button").addClass('visible');
        }
      },
      previousquestion: function() {
        var currentelement = $('#app .questionsection.visible');
        var previouselement = currentelement.prev();
        if (previouselement.hasClass('questionsection')) {
          currentelement.removeClass('visible');
          previouselement.addClass('visible');
        }
      },
      selectanswers: function(temp) {
        for (var i = 0; i < datas.length; i++) {
          if (datas[i].id == temp) {
            datas[i].selectedanswer = $('input[name=optradio]:checked').val();
          }
        }
      },
      checkanswers: function() {
        var score = 0;
        datas.forEach(function(item) {
          if (item.selectedanswer == item.correctanswer) {
            score++;
          }
        });
        console.log(score);
      },
      init: function() {
        view.init();
      }
    };
    var view = {
      init: function() {
        this.maintemplate = $("#app");
        this.nextarrow = $("#next");
        this.submit = $("button");
        this.submit.on('click', function() {
          controller.checkanswers();
        })
        this.nextarrow.on('click', function() {
          controller.nextquestion();
        });
        this.previousarrow = $("#previous");
        this.previousarrow.on('click', function() {
          controller.previousquestion();
        });

        this.render();
      },
      render: function() {
        var maintemplate = this.maintemplate;
        for (var i = 0; i < datas.length; i++) {
          maintemplate.append("<div class='questionsection'><p>" + datas[i].question + "</p></div>");
          for (var j = 0; j < datas[i].options.length; j++) {
            var options = "<div class='radio'><label><input type='radio' name='optradio' questionno=" + datas[i].id + " value=" + datas[i].options[j] + ">" + datas[i].options[j] + "</label></div>"
            maintemplate.children('.questionsection').last().append(options);
          }
        }
        maintemplate.children().first().addClass('visible');
        var radio = $("input[name=optradio]");
        radio.on('click', function() {
          var temp = $(this).attr("questionno");
          controller.selectanswers(temp);
          $(this).attr("checked", "checked");
        });
      }
    };
    controller.init();
  });
});
.questionsection {
  display: none;
}

.btn {
  display: none;
}

.visible {
  display: block;
}

i.fa {
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col-md-2">
      <i id="previous" class="fa fa-arrow-left" aria-hidden="true"></i>
    </div>
    <div id="app" class="col-md-8">
    </div>
    <div class="col-md-2">
      <i id="next" class="fa fa-arrow-right" aria-hidden="true"></i>
    </div>
  </div>
  <button class="btn">Submit</button>
</div>

CodePen http://codepen.io/kannant14/pen/peLOXG

1 个答案:

答案 0 :(得分:0)

解决这个问题的一种方法是在渲染函数中使用问题索引命名您的radiobuttons,如:

var options="<div class='radio'><label><input type='radio' name='optradio"+i+"' questionno="+datas[i].id+" value="+datas[i].options[j]+">"+datas[i].options[j]+"</label></div>"

和selectanswers函数中的相同:

selectanswers:function(temp) {          
  for(var i=0;i<datas.length;i++) {
    if(datas[i].id==temp){
      datas[i].selectedanswer=$('input[name=optradio'+i+']:checked').val();
    }
  }
}

然后你只需要在检查正确的答案时跟踪问题索引。