Below is the code of a read only textbox:
<td>
<input type="text" name="numberAnswer" class="numberAnswerTxt answertxt" id="mainNumberAnswerTxt" onChange="getButtons()" readonly="readonly" >
</td>
Below is the code which displays buttons A-G:
<?php
$a = range("A","G");
?>
<table id="answerSection">
<tr>
<?php
$i = 1;
foreach($a as $key => $val){
if($i%7 == 1) echo"<tr><td>";
echo"<input type=\"button\" onclick=\"btnclick(this);\" value=\"$val\" id=\"answer".$val."\" name=\"answer".$val."Name\" class=\"answerBtns answers answerBtnsOff\">";
if($i%7 == 0) echo"</td></tr>";
$i++;
}
?>
</tr>
</table>
Finally below is the function where it turns on and off the letter buttons:
function btnclick(btn)
{
var context = $(btn).parents('#optionAndAnswer');
if (context.length == 0) {
context = $(btn).parents('tr');
}
if ($(btn).hasClass("answerBtnsOn")) {
$(btn).removeClass("answerBtnsOn").addClass("answerBtnsOff");
return false;
}
if ($(btn).hasClass("answerBtnsOff")) {
$(btn).removeClass("answerBtnsOff").addClass("answerBtnsOn");
return false;
}
$('.answertxt', context).val(context.find('.answerBtnsOn').length > 0 ? context.find('.answerBtnsOn').length : '');
}
What I have been trying to do in this function is that if the user has turned on a button , it should add the number in the texbox. For example, lets say all buttons are off, if I turn on button “B”, then the textbox should display number 1 in the textbox as one button is turned on, if I then turn on button “E”, it should display “2” in the textbox as two button are now turned on and etc. Also if I turn off button “E”, it should go back to displaying “1” in the textbox as only button “B” is turned on. In other words I want to keep track on how many buttons have been turned on.
How can I achieve this because at the moment nothing is being displayed in the text box when I turn a button on.
Here is the demo of the application:
When you open app just click on the “Open Grid” link and select a grid button, when letter buttons appear, then click on the buttons to turn on and off, as you can see nothing is displayd within the textbox.
The line that calculates the number of buttons that have been turned on or off never gets hit because you have
return false;right after you set the button classes. Try this:You may also want to try using jQuery’s
.toggleClass()method. It was made for just this sort of thing.