0

I'm wondering if there is a better way to add/remove checkbox values to an array. Sadly i can't use ECMAScript 5 indexOf() as i need to support IE8/7.

Here is a working jsfiddle example: http://jsfiddle.net/puyQr/

What this Method does is:

/**
 * If a user clicks onto the checkbox, the value of the value attribute is
 * only added to the array when the value not yet exists. However, if
 * the value already exists, the value is removed.
 */

var values = [];
jQuery(':checkbox').on('click', function(){     
    var index = jQuery.inArray(this.value, values);
    if(index === -1) {
        values.push(this.value);
    } else {
        values.splice(index, 1);
    }
});
2
  • You could keep an object as a map and add/remove the checkbox names (or values I guess). It'd be faster, though unless you've got hundreds of checkboxes it'd make no real difference. Commented Jan 11, 2013 at 14:44
  • 3
    MDN has code to support indexOf in those browsers Commented Jan 11, 2013 at 14:45

2 Answers 2

2

Just another way to get values from checkboxes:

var values = jQuery(':checkbox:checked').map(function(){
    return $(this).val();
}).get();

demo

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, use an object literal.

var values = {};
jQuery(':checkbox').on('click', function () {     
    if (this.value in values && values[this.value] === 1) {
        values[this.value] = 0;
    } else {
        values[this.value] = 1;
    }
});

see here.

If you want it as an Array later, converting it is a simple matter, using for..in and checking the value is 1 before keeping the key.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.