2

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?

2 Answers 2

2

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

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

Comments

1

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>

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.