user3708356
user3708356

Reputation: 39

How can I modify my code to select specific checkboxes?

I want to write a simple javascript script to select from a large list of checkbox items on a website. Lets say I want to select the 3rd, 12th, and 25th checkbox. How would I do that? Right now it selects every item.

var script = document.createElement('script');
 script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
 script.type = 'text/javascript';
 document.getElementsByTagName('head')[0].appendChild(script);
$("#detail input:checkbox").click();

Upvotes: 0

Views: 59

Answers (3)

desai
desai

Reputation: 1

<input type="checkbox" name="multi_selection"/>
var idArr = [];
$.each($("input[name='multi_selection']:checked"), function(){            
  idArr.push($(this).val());
});

Now idArr is the array of the selected checkboxes... alert(idArr)

Upvotes: 0

Yared Rodriguez
Yared Rodriguez

Reputation: 141

I will provide a solution in javascript and equivalent jQuery. I added a last solution (my favourite), which would generic, creating a custom pseudo selector.

For javascript, I chose all the inputs and verify their type. Incrementing a counter when the type is checkbox. Then I compare with an array of the indexes I want to select and I push the element to the final array with all my elements (mySelection):

var mySelection = [];
var checkboxIndexes = [3,12,25];
var checkCounter = 0;
var allInputs = document.getElementsByTagName("input");

for(var i=0;i<allInputs.length;i++) {
    if (allInputs[i].type == 'checkbox') {
        if(checkboxIndexes.indexOf(checkCounter) > -1;)
            mySelection.push(allInputs[i]);
        checkCounter++;
    }
}; 

For the jQuery you could use:

$('#detail input:checkbox:eq(index)');

But I did an equivalent to the javascript one using filter. I personally like more this solution since you can put all the index to be selected in one array:

var checkboxIndexes = [3, 12, 25];
var mySelection = $("#detail input:checkbox").filter(function(index) {
    return checkboxIndexes.indexOf(index) > -1;
});

The last solution would be a generic solution which will allow to create a custom pseudo selector that I called "multieq". The goal is to use "multieq" as a filter directly from the selector in this way:

var mySelection = $("input:checkbox:multieq(3, 12, 25)");

And this is the code I used in order to create that pseudo selector:

$.expr[':'].multieq = $.expr.createPseudo ?
    $.expr.createPseudo(function(match) {
        var checkboxIndexes=match.split(',');
        for(var i=0; i<checkboxIndexes.length;i++) checkboxIndexes[i] = parseInt(checkboxIndexes[i], 10);
        var index=-1;   
        return function( elem, doc, isXML ) {
            index++;
            return checkboxIndexes.indexOf(index) > -1;
        };
    }) :
    function( elem, index, match ) {
        var checkboxIndexes=match[3].split(',');
        for(var i=0; i<checkboxIndexes.length;i++) checkboxIndexes[i] = parseInt(checkboxIndexes[i], 10);
        return checkboxIndexes.indexOf(index) > -1;
    };
//Now we can use this:
var mySelection = $("input:checkbox:multieq(3, 12, 25)");

Since 1.8+ $.expr breaks for certain cases and it is not including the param index, it is recommended to use createPseudo(), that is why there is a fallback function for jQuery version under 1.8. createPseudo, does not include index neither but allow us to create the index (as a counter).

I hope it helps!

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

I would use filter() and prop()

var indexesToCheck = [2,11,24];

$("#detail input:checkbox").filter(function(index){
   return $.inArray( index, indexesToCheck ) > -1;
   /* OR something like*/
   return $(this).hasClass('someClass');
}).prop('checked',true);

Since it's not clear how you intend to determine which ones get checked I used a simple array. You could aslo check classes or any other element attributes inside filter using this which would be the instance of each element

References:

filter() docs

prop() docs

Upvotes: 1

Related Questions