+ 1
[jQuery] How to check each class' texts with the same class name and match it with the input value?
I want to check the spans inner texts with the same class name and match it with the input value. But it only alerts false even if the input value matches to the span's inner text. Here's the code: https://code.sololearn.com/Wn1KxZ1J2PUp/#html
12 Réponses
+ 3
Golden Rockstar I'm not sure if that was covered in the jQuery course.
But here's a working code that you can study.
https://code.sololearn.com/WwlQg3J897mk/?ref=app
+ 3
James you are correct, $('.answer') will return all those three words as one.
Golden Rockstar you need to iterate and check on each element with the same class.
Also spaces are counted as a character when matching. So make sure to remove those extra space after each word.
+ 3
Golden Rockstar you can use .eq() to select each span.
Example:
$('.answer').eq(0).text() will return the first span word.
+ 3
James Thank you also for the idea! :)
+ 2
Use a loop and put the condition inside. Like this...
for (var x = 0; x < answer.length; x++){
if (input === answer[x]) {
return true;
}
}
I know I haven't properly defined any variables, but that is how you can loop through to check each one.
EDIT: instead of answer[x], do answer.eq(x) like Jonathan said.
+ 2
$(".answer").length works, to check how many times you should run the loop.
And remove those spaces in your HTML, after MEW and MEWL.
Also, it is case sensitive, but you can use .toUpperCase() to make the input all uppercase.
+ 2
Jonathan Pizarra Maraming salamat! Laking tulong nito. :)
+ 1
Because there are three elements with the class "answer", using $(".answer") makes an array of all three.
EDIT: I'm not certain I am correct. I am not too familiar with jQuery, but I still believe your mistake is in not specifying which span.
+ 1
I just tested it, giving the first span an ID instead of a class, and then changing the jQuery selector to an ID, and the code worked -- but only for the span that I gave the ID, not the other two.
Whether you use IDs or classes, your code will need to loop through each one to test them.
+ 1
James Imagine if you have 20 spans and you'll make a condition for matching the text, you'll also have to make each condition one by one.
+ 1
Jonathan Pizarra Too bad I'm not really familiar with iteration. I mean I know the basics but not yet fully knowledgeable to it. :\
+ 1
Jonathan Pizarra Thanks for that code! I'll try it. But is that code be found somewhere in the course here?