Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery evaluate if checkbox is checked and contains the class true [duplicate]

I'm creating a multiple choice assessment using jQuery. Currently the DOM structure is as follows:

<button class="multiplesubmit">Check Answer</button>
<ul class="multiplechoice_answergroup">
<li class="multiplechoice_answer True"><input class="checkbox" type="checkbox" name="checkbox"> Answer 1</li>
<li class="multiplechoice_answer False"><input class="checkbox" type="checkbox" name="checkbox"> Answer 1</li>
<li class="multiplechoice_answer False"><input class="checkbox" type="checkbox" name="checkbox"> Answer 1</li>
<li class="multiplechoice_answer True"><input class="checkbox" type="checkbox" name="checkbox"> Answer 1</li>
</ul>

I need to write a function that when the button is clicked to see if the checkbox is ticked and that the class name of the li contains 'True'.

So far this is my jQuery:

      $('.multiplechoice_answer .Paragraph').prepend('<input class="checkbox" type="checkbox" name="checkme" />');
      $('.multiplechoice_wrap').prepend('<button class="submit_button multiplesubmit">Check Answer</button>');


      $('.multiplesubmit').click(function() {
        multipleChoiceCheck();

      });

      var multipleChoiceCheck = function() {
        if($('input:checkbox[name=checkme]').is(':checked') && $('.multiplechoice_answer').hasClass('True')) {
          alert('correct!');
        }

};
like image 309
Dondada Avatar asked May 30 '14 18:05

Dondada


1 Answers

$('.multiplesubmit').click(function () {
  var correctAnswers = $(this).next('ul').children('li').filter(function () {
    return $(this).hasClass('True') && $(this).find('input[type="checkbox"]:checked').length>0;
  });
  if(correctAnswers.length>0) {
    alert('found')
  }
});

JSFiddle

Update

As per comments

$('.multiplesubmit').click(function () {
  var correctAnswers = $(this).next('ul').children('li').filter(function () {
    return $(this).hasClass('True') && $(this).find('input[type="checkbox"]:checked').length>0;
  });
  var wrongAnswers = $(this).next('ul').children('li').filter(function () {
    return $(this).hasClass('False') && $(this).find('input[type="checkbox"]:checked').length>0;
  });
  if (correctAnswers.length>0 && wrongAnswers.length<1) {
    alert('found')
  }
});

JSFiddle

like image 98
T J Avatar answered Sep 30 '22 19:09

T J