Radio button in ng-repeat

时间:2018-02-03 08:30:22

标签: javascript jquery angularjs

Though there are many solutions to the questions in the internet.But none of them worked for me.The else statement is always getting executed.If any of the radio button is checked then if statement should be executed.But its not happening.Here is the code-

.html

<div  ng-repeat="question in liveCtrl.questions>
  <input type="radio" name="answerGroup" value="0" id="answerGroup_0">&nbsp;
  {{question.optionA}
  <input type="radio" name="answerGroup" value="1" id="answerGroup_1">&nbsp;
  {{question.optionB}
  <input type="radio" name="answerGroup" value="2" id="answerGroup_2">&nbsp;
  {{question.optionC}
  <input type="radio" name="answerGroup" value="3" id="answerGroup_3">&nbsp;
  {{question.optionD}
  <button data-id="{{liveCtrl.currentPage+1}}" class="subques btn btn-lg btn-
  secondary">Save & Next</button>

</div>

.js

$(document).on('click','.subques',function(){
        var check = true;
        $("input:radio").each(function(){
            if($("input[name='answerGroup']:checked").length == 0){
                check = false;
            }
        });

        if(check){
           var bid=$(this).data('id');
           $("#"+bid).addClass('box-color');
          }else{
            console.log("unchecked");
          }
    });

1 个答案:

答案 0 :(得分:3)

Your code works as expected.

Few corrections!

  • You missed a quotes here "question in liveCtrl.questions>

  • You don't have to loop through $("input:radio"). Simply $("input[name='answerGroup']:checked").length is enough to check any radio button is checked or not

$(document).on('click', '.subques', function() {
  var check = true;

  if ($("input[name='answerGroup']:checked").length == 0) {
    check = false;
  }

  if (check) {
    var bid = $(this).data('id');
    console.log("checked");
  } else {
    console.log("unchecked");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div ng-repeat="question in liveCtrl.questions">
  <input type="radio" name="answerGroup" value="0" id="answerGroup_0">&nbsp; {{question.optionA}
  <input type="radio" name="answerGroup" value="1" id="answerGroup_1">&nbsp; {{question.optionB}
  <input type="radio" name="answerGroup" value="2" id="answerGroup_2">&nbsp; {{question.optionC}
  <input type="radio" name="answerGroup" value="3" id="answerGroup_3">&nbsp; {{question.optionD}
  <button data-id="{{liveCtrl.currentPage+1}}" class="subques btn btn-lg btn-
  secondary">Save & Next</button>

</div>