BroScience
BroScience

Reputation: 1

How to select multiple IDs and check if it has the same text?

function checkIfSomeoneWon() {
    if ($('#b1, #b2, #b3').html() === 'X')
    {
        alert('Someone Won!');
    }
}

I want the function to execute only if all three Ids have the character 'X' on it.

Upvotes: 0

Views: 463

Answers (5)

Indrit Kello
Indrit Kello

Reputation: 1313

function checkIfSomeoneWon() {
var b1 = document.getElementById('b1').value;
var b2 = document.getElementById('b2').value;
var b3 = document.getElementById('b3').value;


if((b1.indexOf("X") !== -1)&&(b2.indexOf("X") !== -1)&&(b3.indexOf("X") !== -1)){
alert('Someone Won!');
}
}

Upvotes: 0

thodinh
thodinh

Reputation: 21

Your condition statement is wrong!

jQuery selector will return you a jQuery object like array, when you get html(), it will return you html in first object e.g

<div>
    <div id="b1">Y</div>
    <div id="b2">X</div>
    <div id="b3"></div>
</div>

result of your condition statement will

$('#b1, #b2, #b3').html() => Y

I don't know what do you want but I thinks your solution is bad when you get html to compare. I thinks you should use checkbox and get their values to compare.

Back to your question, you can use

var result = $('#b1,#b2,#b3').filter(function(i, e){
    return $(e).html() === 'X';
});

if(result && result.length) {
    //TODO something
    alert('Someone Won!');
}

Upvotes: 0

Erazihel
Erazihel

Reputation: 7605

You could set these values in an array then use Array#Filter to check if they all equals to X.

function checkValues() {
  const values = [
    document.getElementById('b1').value,
    document.getElementById('b2').value,
    document.getElementById('b3').value,
  ];

  if (values.filter(a => a.toLowerCase() === 'x').length === values.length) {
    console.log('Someone won');
  }
}
<input id="b1"/>
<input id="b2"/>
<input id="b3"/>
<button onclick="checkValues()">Check values</button>

Upvotes: 2

Rajendran Nadar
Rajendran Nadar

Reputation: 5438

Try this

function check() {
    var one = $('#one').val(), two = $('#two').val();

    if (one.indexOf('x') > -1 && two.indexOf('x') > -1) {
        alert('winner you got the game');
    }
}

This should work.

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Simply use the && operator for this

function checkIfSomeoneWon() {
    if ($('#b1').html() === 'X' && $('#b2').html() === 'X' && $('#b3').html() === 'X')
    {
        alert('Someone Won!');
    }
}

checkIfSomeoneWon();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='b1'>X</span>
<span id='b2'>X</span>
<span id='b3'>X</span>

Upvotes: 0

Related Questions