Hypn0tizeR
Hypn0tizeR

Reputation: 794

Get the number from the element's id

I have some inputs as below:

<input type="hidden" id="selected_id-1" name="id[]" />
<input type="hidden" id="selected_id-2" name="id[]" />
<input type="hidden" id="selected_id-3" name="id[]" />
<input type="hidden" id="selected_id-5" name="id[]" />

The list can contain more than just 4 elements.

So, I would like to extract the highest number (in our case = 5) from the ids of elements named "id".

Pure JavaScript needed.

EDIT: Thank you everybody who answered my question.

Upvotes: 0

Views: 4138

Answers (7)

bfavaretto
bfavaretto

Reputation: 71908

Assuming your elements might not be ordered by id, you'll have to check them all to find the highest one.

var inputs = document.getElementsByTagName('input');
var highest = 0;
for(var i=0; i<inputs.length; i++) {
    if(inputs[i].name == 'id[]') {
        var current = inputs[i].id.split('-')[1];
        highest = (current > highest) ? current : highest;
    }
}
// Now highest contains the highest numeric id
console.log(highest);

Upvotes: 3

Gyan Chandra Srivastava
Gyan Chandra Srivastava

Reputation: 1380

function check(){
 var form = document.forms[0];
 var txtS =  form["id[]"];
 var len = txtS.length;
var numb =txts[len-1].split('-')[1]
}

or you can use

var elementgroup = document.getElementsByName("id[]");
var nub= elementgroup[elementgroup .length - 1].split('-')[1];

Upvotes: 1

Ethan Brown
Ethan Brown

Reputation: 27282

Assuming your form is the first one on the page, you can do something like this:

var c = document.forms[0].children;

for( var i=0; i<c.length; i++ ) {
    var prefix = "selected_id-";
    if( c[i].id.search( prefix )===0 )
        console.log( c[i].id.substring( prefix.length ) );
}

Upvotes: 1

epascarello
epascarello

Reputation: 207501

This assumes that the elements are in numerical order.

var elems = document.getElementsByName("id[]");
//or var elems = document.getElementById("formId").elements["id[]"];
//or var elems = document.formName.elements["id[]"];
//or var elems = document.forms[0].elements["id[]"];//0 is the index of the form on the page
var lastElem = elems[elems.length-1];
var lastId = lastElem.id;
var parts = lastId.split("-");
var num = parts[1];
alert(num);

If they are not in numerical order you would need to loop through and keep track.

function getNumber(elem){
    return parseInt(elem.id.split("-")[1],10);
}

var elems = document.getElementsByName("id[]");
var max = getNumber(elems[0]);
for (var i=1;i<elems.length;i++) {
    var num = getNumber(elems[i]);
    if (num>max) {
        max = num;
    }
}
alert(max);

Upvotes: 2

Pete
Pete

Reputation: 2558

It's much easier to do this with something like jQuery because it will handle all the hard parts for you. But if you're using a modern browser, you can do it like this:

var highestNum = (function() {
    var highest = 0, r = /\-(\d+)$/, i, elems = document.getElementsByName("id[]");
    for(i=0; i<elems.length; i++) {
        highest = Math.max(highest, +elems[i].id.match(r)[1]);
    }

    return highest;
});

This accounts for the elements being potentially out of order, too. Though it relies on a pretty new browser to work (IE>=8 or anything that's not IE). If you want fallback support to things like IE6, your best bet is to use jQuery or another such library. With jQuery, the solution would be something like this:

var highestNum = (function() {
    var highest = 0, r = /\-(\d+)$/;

    $("input[name='id[]']").each(function() {
         highest = Math.max(highest, +this.id.match(r)[1]);
    });

    return highest;
});

UPDATE: I cheated a bit off someone else's solution and made it more IE6-friendly. The jQuery solution is still a bit simpler, but the vanilla solution should suit your needs.

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95508

var number = element.id.replace(/^[^\d]+/, "");

or

var number = element.id.match(/\d+/)[0];

EDIT: Just saw that you wanted to get the last element:

var elements = document.getElementsByName("id[]");
var element = elements[elements.length - 1];

Now you can use either of the methods I have shown above the edit.

Upvotes: 6

David Thomas
David Thomas

Reputation: 253308

You can use either regex or slice():

var num = this.id.match(/(\d+)/)[0];

JS Fiddle demo.

Or, with slice:

var num = this.id.slice(-1);

JS Fiddle demo.

The option with slice(), though, will work only with a single-digit number.

Upvotes: 2

Related Questions