Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  92] [ 5]  / answers: 1 / hits: 28037  / 13 Years ago, thu, december 1, 2011, 12:00:00

I have some buttons below in my HTML:



<p>
<input class=answerBtns name=answer type=button value=A />
<input class=answerBtns name=answer type=button value=B />
<input class=answerBtns name=answer type=button value=C />
<input class=answerBtns name=answer type=button value=D />
<input class=answerBtns name=answer type=button value=E />
</p>


What I want to know if lets say I want the user to select 3 buttons for example, then if the user clicks on a button, it will highlight the button in a color (lets say green) but the user can only have three buttons selected. If an additional button is clicked then that button would not be selected. The additional button can only be selected if the user unselects a selected button and then selects the button he wishes. This means that only 3 buttons can be selected at maximum.



My question is that what functions in Javacsript can be used to be able to do this?



Thank You


More From » select

 Answers
3

Firstly, you have to give your buttons different names.



<input class=answerBtns id=answer1 type=button value=A onclick=changeClass(this.id); /> 
<input class=answerBtns id=answer2 type=button value=B onclick=changeClass(this.id);/>
<input class=answerBtns id=answer3 type=button value=C onclick=changeClass(this.id);/>
<input class=answerBtns id=answer4 type=button value=D onclick=changeClass(this.id);/>
<input class=answerBtns id=answer5 type=button value=E onclick=changeClass(this.id);/>


What I would suggest is using jquery to change the class of the button to something like answerBtnsSelected when a button is selected this, will also help you with your css styles to highlight the button.



What you can then do is create a function that checks the amount of buttons with that class, and if it's three or more then ignore or whatever, else change the class to make it selected.



Added logic to unselect button



function changeClass(id)
{
if ($('#' + id).hasClass('answerBtnsSelected'))
$('#' + id).removeClass('answerBtnsSelected');
else
{
if ($('.answerBtnsSelected').length < 3)
{
$('#' + id).addClass('answerBtnsSelected');
}
else
{
alert('Only three buttons can be selected.');
}
}
}

[#88804] Wednesday, November 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leannjaidynd

Total Points: 111
Total Questions: 100
Total Answers: 94

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;