Unable to compare two strings in jquery

Could someone please help me on this issue? My html code is

<div class="py-2 h5"><b>1 can arbitration agreement be in oral?</b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3 mcq activated" id="options"> 
<label class="options">Yes<input type="radio" class="radio" name="radio1"> <span class="checkmark"></span></label>
<label class="options">no<input type="radio" class="radio" name="radio1"> <span class="checkmark"></span></label>  
<label class="options">yes, if turnover is below 10 Lakhs<input type="radio" class="radio" name="radio1"> <span class="checkmark"></span></label>                        
<label class="options">None of the above<input type="radio" class="radio" name="radio1"> <span class="checkmark"></span></label>                        
<label class="options reveals"><p class="radio reveal text-center btn btn-info">no</p></label>
</div>   

My jquery code is

 $('.radio').click(function(){
  $(this).parents(".options").parent().addClass('activated'); 
   var selected = ($(this).parent().text());
 var answer = ($(this).closest(".mcq").find(".reveal").text());
  if(selected === answer){
  alert("yes");
}else{
  alert("nope");
}
});

My desired output should be for example in this case whenever a user clicks second radio option i.e “no” it should check the answer with the last radio option i.e “no” and if both are matching, then I should get a alert(“yes”). I have been struggling with this. Any help is highly appreciated

Answer

You have to remove the spaces between the <input> fields and the <span>. .text() gets all text between all tags so your desired answer in your example is “no ” instead of “no”:

$('.radio').click(function(){
  $(this).parents(".options").parent().addClass('activated'); 
   var selected = ($(this).parent().text());
 var answer = ($(this).closest(".mcq").find(".reveal").text());
  if(selected === answer){
  alert("yes");
}else{
  alert("no");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="py-2 h5"><b>1 can arbitration agreement be in oral?</b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3 mcq activated" id="options"> 
<label class="options">Yes<input type="radio" class="radio" name="radio1"><span class="checkmark"></span></label>
<label class="options">no<input type="radio" class="radio" name="radio1"><span class="checkmark"></span></label>  
<label class="options">yes, if turnover is below 10 Lakhs<input type="radio" class="radio" name="radio1"><span class="checkmark"></span></label>                        
<label class="options">None of the above<input type="radio" class="radio" name="radio1"><span class="checkmark"></span></label>                        
<label class="options reveals"><p class="radio reveal text-center btn btn-info">no</p></label>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *