raghu raman
raghu raman

Reputation: 49

how to check more than one class name in js

<script src="https://code.jquery.com/jquery-1.12.4.min.js">
      var answers = ["A","C","B"], 
        tot = answers.length;
    function getScore(){
      var score = 0;
      for (var i=0; i<tot; i++)
        if($("input[class='question0']:checked").val()===answers[i])    //TODO add another classes like question1,question2,etc..

         score += 1; // increment only
      return score;
    }
    
    function returnScore(){
     
      $('p').html('Score: ' + getScore()  + '');
    }
    </script>

here in this line,

if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..

how to check for more than one classes? question+i is possible? or how to mention many classes? thanks in advance senior!

Upvotes: 1

Views: 47

Answers (2)

Nhokchien
Nhokchien

Reputation: 11

This is the way to select multiple classes in JQuery

$("input[class*=question]")

Try the full code

var answers = ["A", "C", "B", "D"];
var inputList = $("input[class*=question]");
inputList.change(returnScore);
function getScore() {
  var score = 0;
  inputList.each(function (i) {
    if ($(this).val() === answers[i] && $(this).is(":checked")) score += 1;
  });
  return score;
}

function returnScore() {
  $("p").html("Score: " + getScore() + "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div>answers = ["A", "C", "B", "D"]</div>
<div>
  <input class="question0" type="checkbox" id="question0" value="A"/>
  <label for="question0">This is Question 0, value: A</label>
</div>

<div>
  <input class="question1" type="checkbox" id="question1" value="C"/>
  <label for="question1">This is Question 1, value: B</label>
</div>

<div>
  <input class="question3" type="checkbox" id="question3"  value="R"/>
  <label for="question3">This is Question 3, value: R</label>
</div>

<div>
  <input class="question4" type="checkbox" id="question4" value="F"/>
  <label for="question4">This is Question 4, value: F</label>
</div>

<p></p>

Upvotes: 1

Matt Davis
Matt Davis

Reputation: 1337

You can just format i into your string like so:

for(let i = 0; i < tot; i++) {
   if($(`input[class='question${i}']:checked`).val() === answers[i])
      score++;
}

In general you can use string literals like so using the backtick character `:

let variable = "value";
console.log(`A sentence containing a ${variable}`);

Upvotes: 1

Related Questions