12

How do you get the proper index of a selected input from a set of input elements with irregularly numbered indexes using JQuery? JQuery's "index" function always returns a value starting from 0 instead of the indexes I used. My code is below:

JQuery:

$("input[name^=myboxes]").click(function() {
        var element_id = $("input[name^=myboxes]").index(this);
        alert(element_id); //will alert 0, 1, or 2 instead of 3, 8, or 10
});

HTML:

<input type="checkbox" id="myboxes[3]" name="myboxes[3]" value="CHECKED"  >
<input type="checkbox" id="myboxes[8]" name="myboxes[8]" value="CHECKED"  >
<input type="checkbox" id="myboxes[10]" name="myboxes[10]" value="CHECKED" CHECKED >

Thank you!

4 Answers 4

7

The following is what has always worked for me.

JQuery:

$("input[name^=myboxes]").click(function() {
        var element_id = $(this).attr("meta:index");
        alert(element_id);
});

HTML:

<input type="checkbox" id="myboxes[3]" name="myboxes[3]" meta:index="3" value="CHECKED"  >
<input type="checkbox" id="myboxes[8]" name="myboxes[8]" meta:index="8" value="CHECKED"  >
<input type="checkbox" id="myboxes[10]" name="myboxes[10]" meta:index="10" value="CHECKED" CHECKED >

Hope this helps.

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

1 Comment

Similar concept to use is data- attributes.
7

The selected answer has a few issues with syntax it should be:

$("input[name^=myboxes]").click(function() {
    var element_id = $(this).attr('id');
    //the initial starting point of the substring is based on "myboxes["
    var ix = element_id.substring(8,element_id.length - 1);
    alert(ix);
});

Comments

5

The value of your ID does not have an "index" property. It's just a string.

One suggestion: parse the id string to get your value:

$("input[name^=myboxes]").click(function() {
    var element_id = $(this).attr('id');
    //the initial starting point of the substring is based on "myboxes["
    var ix = element_id.substring(8,element_id.length - 1)
    alert(ix);
});

Hope this helps

Comments

0

it would be even shorter if you do it like this:

   var id = $(this).attr('id');
       // remove everything that is not a number
       id = id.replace(/[^0-9]/g, '');
       alert(id);

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.