I have some inputs and I'm looking to use jQuery select the one with the highest array index for its name attribute
<input name="option[3]"/>
<input name="option[2]"/>
<input name="option[8]"/> <!-- <----- -->
<input name="option[4]"/>
<input name="option[1]"/>
<input name="option[5]"/>
I was able to achieve this with the following code:
var options = [];
$('[name]').filter(function (i, e) {
return $(e).attr('name').match(/option\[\d+/) // [name=option[n
}).each(function (i, e) {
options.push($(e).attr('name').replace(/option\[(\d+)\]/, '$1')); // [3,2,8,4,1,5]
});
options.sort(); // [1,2,3,4,5,8]
var $option = $('[name="option[' +
options.slice(options.length - 1, options.length) +
']"]'); // [name="option[8]"]
But the whole thing seems a bit over kill to me and I was wandering if there is a simpler way?