andrew
andrew

Reputation: 9593

Selector to get input based on name array index

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?

Upvotes: 2

Views: 1080

Answers (2)

rrk
rrk

Reputation: 15875

var $test = $("input[name^=option]").sort(function(a,b){
    var aID = a.name.replace(/option\[(\d+)\]/, '$1');
    var bID = b.name.replace(/option\[(\d+)\]/, '$1');
    return aID < bID ? -1 : 1;
});
$test.last().remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="a">
<input name="option[3]" value="3"/>
<input name="option[2]" value="2"/>
<input name="option[8]" value="8"/> 
<input name="option[4]" value="4"/>
<input name="option[1]" value="1"/>
<input name="option[5]" value="5"/>
</div>

Upvotes: 1

j08691
j08691

Reputation: 208030

Three lines of code can do it:

var ary = [];
$('input').each(function(){ ary.push($(this).attr('name').match(/\d+/g)[0]) })
$('input[name=option\\['+ Math.max.apply(null, ary)+'\\]]').css('background','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input name="option[3]"/>
<input name="option[2]"/>
<input name="option[8]"/> 
<input name="option[4]"/>
<input name="option[1]"/>
<input name="option[5]"/>

The first line declares an empty array.

The second line iterates over the inputs and pushes the number from the name attribute's value onto the array using a simple regex

The last line selects the input using Match.max to pick the largest number from the array

Upvotes: 2

Related Questions