3

I have many elements with same name:

<input type="text" name="Education[GraduationDate][0]" />
<input type="text" name="Education[GraduationDate][1]" />
<input type="text" name="Education[GraduationDate][2]" />
<input type="text" name="Education[GraduationDate][3]" />

I want jquery give me the index number of selector name, so if I select first one give me number (0), and so on.

I did this with jquery:

 var arrayname = $(this).attr('name');
 var arrayindex = arrayname.substring(24,25);

arrayindex return me the Index that I want, but I think this is not good way to do that, because maybe You have index with 2 digit number, so the substring not work fine.

Please advice ..

3 Answers3

5

need it with Education[GraduationDate] not only Education

Try using .index() with "input[name^=Education]" "input[name^=Education\\[GraduationDate\\]]" passed as selector parameter

.index( selector )

selector

Type: Selector

A selector representing a jQuery collection in which to look for an element.

$("input").change(function() {
  console.log($(this).index("input[name^=Education\\[GraduationDate\\]]"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="Education[GraduationDate][0]" />
<input type="text" name="Education[GraduationDate][1]" />
<input type="text" name="Education[GraduationDate][2]" />
<input type="text" name="Education[GraduationDate][3]" />
guest271314
  • 1
  • 10
  • 82
  • 156
2

You can use

$("[name^='Education[GraduationDate]']").index(this)

Fiddle

Anoop Joshi
  • 24,460
  • 8
  • 28
  • 49
0

hope this can help you:

...
var name = ($this).attr('name'); 
var digits = name.match(/\d+/g)
var index = digits.pop() // suppose your name has more than one digit, the last one is what you want(index) 
...
FelixHo
  • 960
  • 9
  • 24