2

How can i select checkbox which contains number in range of numbers (numbers are not repeated) in data attribute. Lets say i have these two checkboxes:

<input type="checkbox" name="A" data-numbers="1,3,2" />
<input type="checkbox" name="B" data-numbers="34,21,11,39,8,6,33" />

and i want to select checkbox by number 3.

Because number 3 is second number in first checkbox data-numbers, it should match and select first checkbox.

1
  • change to array format data-numbers="[1,2,3]" and jQuery.data() will parse as array automatically, then use array methods Commented Dec 5, 2014 at 15:11

3 Answers 3

3

You can filter the jQuery objects.

var num = "3";
var elem = $('[date-numbers]').filter(function(){
   return $(this).data("numbers").split(",").indexOf(num) > -1;
});

What you're doing is filtering based on splitting on , and then checking if the num is present in it.

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

1 Comment

For some reason, it gives me "Cannot read property 'split' of undefined". But when i console.log($(this).data('numbers')) it shows me those numbers.
1

This answer uses the same technique as @AmitJoki's but transfers some processing to the markup, if you're open to suggestions. By changing "1,3,2" to "[1,3,2]" ....., the code becomes:

var num = 3;
$(':checkbox').filter(function() {
    return $(this).data('numbers').indexOf( num ) > -1;
})
.prop('checked', true); //or whatever other processing you'd like to perform

$(function() {
    //not required .. just for demo purposes
    $(':checkbox').after(function() {
        return $('<label/>', {text: $(this).data('numbers')});
    });

    var num = 3;
    $(':checkbox').filter(function() {
        return $(this).data('numbers').indexOf( num ) > -1;
    })
    .prop('checked', true); //or whatever other processing you'd like to perform
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="A" data-numbers="[1,3,2]" />
<input type="checkbox" name="B" data-numbers="[34,21,11,39,8,6,33]" />

Comments

0

Loop through all inputs with 'data-numbers' set the attr checked if the index of your value to located is found

$("input[data-numbers]").each(function() {
    $(this).attr("checked", $(this).attr('data-numbers').indexOf(",3,") > -1);
});

http://jsfiddle.net/Mutmatt/jfzpakru/

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.