Reputation: 1279
I have dynamic text boxes that cascade down the page. When a refresh happens, I need to be able to assess how many text-Boxes the user has added to the page.
So the user will click "Add Box" and this will generate a new textbox with id = doc0
, add another will be id = doc1
and so on.
The issue is on refresh, I am not able to check at what increment the user reached.
I tried the starts with approach, but could not get what length was returned.
$('[id^=document]')
Ideally, on entering the page, it gets all ids starting with document and tells me what the highest value it has found proceeding it.
EG:
<div id="doc1">some elements inside</div>
<div id="doc2">some elements inside</div>
<div id="doc3">some elements inside</div>
<div id="doc4">some elements inside</div>
Answer value 4 found.
Upvotes: 1
Views: 3163
Reputation: 67505
You could use count if the id's are always ordered like :
$('[id^=doc]').length;
console.log( $('[id^=doc]').length );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="doc1">some elements inside</div>
<div id="doc2">some elements inside</div>
<div id="doc3">some elements inside</div>
<div id="doc4">some elements inside</div>
Else you could retrieve the number from the last matched element like :
$('[id^=doc]').last().attr('id').split('doc')[1]
console.log( $('[id^=doc]').last().attr('id').split('doc')[1] );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="doc1">some elements inside</div>
<div id="doc2">some elements inside</div>
<div id="doc3">some elements inside</div>
<div id="doc4">some elements inside</div>
Upvotes: 2
Reputation: 122057
You can return array of numbers from id
's with map()
and get()
and then use Math.max
to return highest number.
var value = Math.max(...$('[id^=doc]').map(function() {
return parseInt($(this).attr('id').match(/\d+$/));
}).get());
console.log(value)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="doc1">some elements inside</div>
<div id="doc2">some elements inside</div>
<div id="doc10">some elements inside</div>
<div id="doc4">some elements inside</div>
Upvotes: 0