Javascript function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Javascript function

I want when someone click on the button it will turn blue and other turn grey.and they cannot select more than one.help me it's my first project https://code.sololearn.com/WqIE9mKl859H/?ref=app

16th May 2020, 4:21 PM
Shubham Thakur
Shubham Thakur - avatar
8 Answers
+ 3
You really need to add the six missing closing div tags. Doing this will help you limit the number of buttons you turn grey to just the 3 buttons for the current question. Also with your code as is, you should either pass 'this' or 'event' to the result function this will help you to know which button was pressed therefore which button background color should change to blue. https://code.sololearn.com/Wtg68OXkw2pT/#js
17th May 2020, 8:03 PM
ODLNT
ODLNT - avatar
+ 2
The issue is that "getElementsByClassName" returns an array. That means you have to cycle through each element of that array and make your alterations. const btn = document.getElementsByClassName("btn"); for (let i = 0; i < btn.length; i++) { btn[i].style.background = "grey"; }
16th May 2020, 5:13 PM
Russ
Russ - avatar
+ 1
I think your main issue here is that all of your buttons (from all questions) have te same class name. My advice is that you change the classnames to something like "btnq1", "btnq2", etc. then you can change only the buttons you need to. I have amended your code to this. I don't know if there is an easier way to do this, but I created a new event listener (JS Tab, line 43) and added the "e" parameter to your result function. I couldn't get this to work with the function call in the HTML. Note that some class names have been changed so some things may look a little different to normal. https://code.sololearn.com/Wg2178nCpgAU/?ref=app
16th May 2020, 5:43 PM
Russ
Russ - avatar
+ 1
Thankyou for the help ..but I think caz it was my idea so I have learn and do it myself..your help was wonderful but even after that I m not getting what I want ..thankyou again.
16th May 2020, 6:00 PM
Shubham Thakur
Shubham Thakur - avatar
+ 1
Sorry I can't be more help. Javascript is not my most favoured language. But good luck! 👍
16th May 2020, 6:02 PM
Russ
Russ - avatar
0
With this all of them are turning grey while clicking.. but I want the clicked one stays blue ...and other gets grey... How it will be done.
16th May 2020, 5:21 PM
Shubham Thakur
Shubham Thakur - avatar
0
🙂
16th May 2020, 6:03 PM
Shubham Thakur
Shubham Thakur - avatar
0
Wow thankyou
18th May 2020, 2:50 PM
Shubham Thakur
Shubham Thakur - avatar