Jameson Reden Jameson Reden - 1 month ago 6
jQuery Question

Comparing Elements inside an If else condition in Jquery

This is my first time asking here on Stackoverflow,

Here is my HTML code,



<div id="accordion" style="height: auto;">
<h3>Question 1</h3>
<div>
<div id="q1">
Sending messages from another user's email address is called what?
<ul>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton" data-optionId="option1">Spamming</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton" data-optionId="option2">Trolling</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton answer active clicked" data-optionId="option3">Spoofing</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton" data-optionId="option4">Pharming</button></li>
</ul>
</div> <!-- q1 -->
</div>
<h3>Question 2</h3>
<div>
<div id="q2">
How many zebibytes are in a yobibyte?
<ul>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton answer" data-optionId="option1">1,024</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton" data-optionId="option2">1,048,576</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton" data-optionId="option3">1,000,000</button></li>
<li><button type="button" class="btn btn-secondary btn-sm optionbutton active clicked" data-optionId="option4">1,000,000,000</button></li>
</ul>
</div><!-- q2 -->
</div>





And Here is my Jquery Code



var q1input = 0;
var q2input = 0;
var q3input = 0;
var q4input = 0;
var q5input = 0;
var optionele1 = $("#q1").find("button.active.clicked");
var optionele2 = $("#q2").find("button.active.clicked");
var optionele3 = $("#q3").find("button.active.clicked");
var optionele4 = $("#q4").find("button.active.clicked");
var optionele5 = $("#q5").find("button.active.clicked");
var answerele1 = $("#q1").find("button.answer");
var answerele2 = $("#q2").find("button.answer");
var answerele3 = $("#q3").find("button.answer");
var answerele4 = $("#q4").find("button.answer");
var answerele5 = $("#q5").find("button.answer");
if( optionele1.is(answerele1) ){ q1input = 100; }else{}
if( optionele2.is(answerele2) ){ q2input = 100; }else{}
if( optionele3.is(answerele3) ){ q3input = 100; }else{}
if( optionele4.is(answerele4) ){ q4input = 100; }else{}
if( optionele5.is(answerele5) ){ q5input = 100; }else{}





The question is, How should I compare the two elements in jquery? or there any wrong syntax in my code? Help please. I'm stuck here.

Answer

You need to compare the first elements in the jQuery objects to one another. For example:

if( $('.sel1')[0] == $('.sel2')[0] )

So your code should look as follows (note that there's no need for the else block, either):

if( optionele1[0] == answerele1[0] ) { q1input = 100; }
// etc.