Incorrect number is displayed (Jquery)

I have a number of Answers textbox which the user enters in the number of answer he/she like to select. Now lets say the user opens the grid and selects option “5” and clicks on the “Select All Answers” buttons, all the 5 buttons “A” to “E” turn greeen and it will state 5 in the Number of Answers Text-Box.

But problem is that if I change the option from the grid from “5” to “3”, then you will see 3 buttons “A” to “C” all selected which is fine but problem is that it still states the number “5” in the Number of Answers Text-Box when it should state 3 because there are 3 buttons selected (not because it displays 3 buttons, it is because 3 buttons are selected (have turned green).

So How can I get it so that the text-box displays the correct number of buttons selected from the buttons displayed on screen?

This line of code you need to look at is in the $(“.gridBtns”).click(functions():


 $('#numberAnswerTxt').val($('.answerBtnsOn:visible').length)

Follow steps below in my jsfiddle:

  1. Open the Grid and select option “5”. Buttons A to E would appear.
  2. Click “Select All Answers” buttons. All buttons A to E would be selected (turn green) and the “Number of Answers” textbox would display the number 5.
  3. Now Open the Grid again and select option “3”. As you can see buttons A to C would appear and are all selected (turn green). Yet the textbox still displays the number 5. This should display number 3.

code in jsfiddle, click here

Do you have to use jquery?

All the functionality you describe can be done with much less code than what you have by using plain javascript.

The jquery you have there is messy.

It doesn’t have to be jquery. If you know a solution in simple javascript then that is fine by me :slight_smile:

It’ll be quicker for me if you at least try to do it using plain javascript first if you are interested and then someone can help you get it working if you get stuck rather than me starting from scratch.

Well the fact is my application was in plain javascript but I have been told that jquery is much better to use as that requires less coding. I won’t change my coding to simple javascript because there is too much to code, I don’t mean the fiddle that has been really shortened to fit this question, my full code is about 800 lines long

If you go look at how much more code jquery runs in the background to perform a given task you will find that it is much, much more than the code that would be required to perform the same task with plain javascript.

I assume you are aware that jquery is nothing more than javascript functions prewritten by someone else to perform common tasks. There is absolutely nothing you can do with jquery that you cannot do using plain javascript because jquery is javascript :slight_smile:

You can code up the functionality you describe with much less plain javascript code than the amount of jquery code you have.