mercredi 20 décembre 2017

Can you target multiple values with a single input type?

I need certain checkbox values to be unique only based on the value. I could probably add a class to any checkboxes that have these values and look for the class, but I'd still like to keep the focus on the value alone. Is there a way to add unique values without writing so much duplicate code? This is what I want in the most basic form:

var unique = $('.myclass input[type=checkbox][value=1], .myclass input[type=checkbox][value=3], .myclass input[type=checkbox][value=abc], .myclass input[type=checkbox][value=bca], .myclass input[type=checkbox][value=255], .myclass input[type=checkbox][value=abc123]');
unique.click(function() {
    unique.filter(':checked').not(this).removeAttr('checked');
});

This has more code, but it isn't as messy if the unique values array needs to keep growing.

var uniqueValues = ["1", "3", "abc", "bca", "255", "abc123"];
var uniqueArray = [];
$.each(uniqueValues, function( index, value ) {
    uniqueArray.push('.myclass input[type=checkbox][value='+value+']');
});
var unique = $(uniqueArray.join(", "));
unique.click(function() {
    unique.filter(':checked').not(this).removeAttr('checked');
});

Is there a way to do something like this that would be the same as one of the two above examples?

var uniqueValues = ["1", "3", "abc", "bca", "255", "abc123"];
var unique = $('.myclass input[type=checkbox][value='+uniqueValues+']');
unique.click(function() {
    unique.filter(':checked').not(this).removeAttr('checked');
});




Aucun commentaire:

Enregistrer un commentaire