Dat Lam
Dat Lam

Reputation: 171

jQuery get attribute from dynamic tag

I have this html

<div class="form-new"><input name="a1" /></div>
<div class="form-new"><input name="a2" /></div>
<div class="form-new"><input name="a4" /></div>
<div class="form-new"><input name="a3" /></div>

...

it dynamic so I want use jquery to get biggest number on the end of the name of input(in this example, it will be a4 ), plz tell me how to do this, sorry for my bad english

Upvotes: 1

Views: 979

Answers (4)

Miguel
Miguel

Reputation: 20633

Vanilla JS

var largest = [].slice.call(document.querySelectorAll('.form-new')).reduce(function (acc, el) {
    var name = el.querySelector('input').getAttribute('name');
    return int(name) > int(acc) ? name : acc;
});

function int(s) { return parseInt(~~(s+'').replace(/.*[^\d](\d+)$/g,'$1')); }

http://jsfiddle.net/j91x5asd/8/

Upvotes: 1

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

You can just write it up as below:

DEMO HERE

var ip=$('.form-new input');
var numbers=[];
var maxNum=0;
$.each(ip,function(index,value){
    numbers.push([value["name"].split("a")[1],value]); //storing along with control so that you can refer in in future if you want
});

$.each(numbers,function(index,value){
     if(value[0]>parseInt(maxNum))
     {
          maxNum=value[0];
     }
});
alert("a"+maxNum);

Upvotes: 1

JGV
JGV

Reputation: 5187

Here is a possible solution:

Sort the values in div and display the last one.

var inputList = $('input').sort(function (a, b) {

      var contentA =$(a).attr('name');
      var contentB =$(b).attr('name');
      return (contentA > contentB);
   })

var totalInputItems = inputList.length;

alert($(inputList[totalInputItems-1]).attr('name'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-new"><input name="a1" /></div>
<div class="form-new"><input name="a2" /></div>
<div class="form-new"><input name="a4" /></div>
<div class="form-new"><input name="a3" /></div>

Upvotes: 1

Ahmad Ibrahim
Ahmad Ibrahim

Reputation: 1925

var maxVal = -1;        // set to the minimum possible value
var maxInput;
$('.form-new input').each(function (i, e) {
    var val = parseInt($(e).attr('name').match(/\d+$/)[0]);    // gets the number at the end of "name" attribute value
    if (val > maxVal) {
        maxVal = val;
        maxInput = $(e);
    }
});

// maxInput holds the jQuery object of the input with max value at the end of "name" attribute

Upvotes: 2

Related Questions