Anthony
Anthony

Reputation: 35978

how to prevent a checkbox to be selected using jquery

I am showing a form to the user with few checkboxes. Some of them will be pre-selected and some won't be.

like below:

<input type="checkbox" name="box" value="9"> nine
<input type="checkbox" name="box" value="10"> ten
<input type="checkbox" name="box" value="11"> eleven
<input type="checkbox" name="box" value="12" checked> twelve

Please note that in the last checkbox the checked keyword is added using a scriplet.

Now, even when I physically deselect check twelve, my javascript code doesn't understand that the checkbox is no longer selected.

Update I pasted the wrong link earlier. Here is the updated jsfiddle link: http://jsfiddle.net/JLSUK/20/

What I'm trying to accomplish alert the user ONLY when they have selected checkbox twelve. However, even if that checkbox is not selected, I'm getting an alert that it IS selected. I think this is because I have checked in the actual HTML content, however, I can't remove that since the first time the page loads, I have to show to the user that they had this particular checkbox selected.

Is this doable with jQuery?

Upvotes: 0

Views: 100

Answers (2)

Curtis
Curtis

Reputation: 103368

In your jsfiddle you have:

$('#update').click(function () {

Whereas your input is:

<input type="submit" id="something" value="update" /> 

​Try changing your jquery to:

$('#something').click(function () {

The #* selector in jQuery is referring to the id, not the value.


Also you have:

if (jQuery.inArray('8', selected) >= 0 && jQuery.inArray('11', selected) >=0)

None of your checkboxes have a value of 8 so this will never be "true".


Also declare the array as a new array:

var selected = new Array();

SEE WORKING DEMO

Select "eight" and "eleven" and your popup will appear


EDIT: After seeing question edit, you need to add the following line to clear the previous array items:

var selected = [];

http://jsfiddle.net/JLSUK/20/

Upvotes: 1

Igor
Igor

Reputation: 33993

You are adding elements to the array, but you are never removing them. So every time the user clicks 'update', you are simply filling your array. At some point you either need to clear the array, or remove the previous selection from it (depending on your exact logic).

Upvotes: 1

Related Questions