+ 1

Please help~

There are order lists. When I put any number into input box, the number list changed color into red. For example, if I put number 1 into input box, lists of number1(1.a)should be changed the color into red. The problem is color changed following by index. If I put number2, lists of number 3(3.c) is changing instead of number 2(2.b). How can I fix it? Also, how can I remove red color after clear the input field, so that I can type new number again and the color change again. Please help~~ Html. <ol id="list-container"> <li>a<li> <li>b<li> <li>c<li> <li>d<li> <li>e<li> </ol> <input type="text" id="number" autofocus> <button id="changeColor">color Change</button> Jquery var lists=$("li"); $("#changeColor").click(function (){ var num=$("#number").val().split(","); $.each(num,fucntion(i){ lists.eq(num[i]).addClass("red"); $("#number").val(""); }); });

23rd Mar 2023, 12:44 AM
Hannah
7 odpowiedzi
+ 4
You said it colors the wrong item. You need to minus 1 from the number because arrays first index is 0. To clear the colors, It checks if the input is empty, if so, remove the classes.
23rd Mar 2023, 3:49 AM
Toni Isotalo
Toni Isotalo - avatar
+ 3
var lists=$("li"); $("#changeColor").click(function(){ var num=$("#number").val().split(","); if($.trim($("#number").val()) != "") { lists.removeClass("red"); $.each(num, function(i) { lists.eq(num[i-1]).addClass("red"); $("#number").val(""); }) } else { lists.removeClass("red"); } });
23rd Mar 2023, 3:46 AM
Toni Isotalo
Toni Isotalo - avatar
+ 3
You have some typos in your code. In your html, closing tags should be </li> And in your jquery I am sure "fucntion" is a syntax error. It would be better if you link to a working version of your code next time. Javascript array indices start from 0. So the second element of an array has index 1, etc. To remove colors, loop through all the list items and check if its index+1 is the same as the one specified. If not, remove the coloring. If yes, add the color. I am not familiar with jquery, but here is a working variation in vanilla js. https://code.sololearn.com/W1VuAUWyrEza/?ref=app
23rd Mar 2023, 4:01 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Wow~ Toni Isotalo~ Thank you so much!! 🙏 I've been struggling with this pb for 4 days. Thank you SO SO Much~~~~ :)
23rd Mar 2023, 10:18 AM
Hannah
+ 1
And your explanation was perfect to understand!! Thank you again~~
23rd Mar 2023, 10:21 AM
Hannah
+ 1
Thank you so much Tibor Santa~ I didn't know there is working version of my code ^^;. Thanks for letting me know!! I am very bigginer for this. Haha. Thank you so much~
23rd Mar 2023, 10:25 AM
Hannah
+ 1
Also Thank you so much your link for your working version. It really helped also. :)
23rd Mar 2023, 10:27 AM
Hannah