Blawless Blawless - 4 months ago 20
CSS Question

Jquery / javascript selector for id starts with specific text and get highest value it ends in

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.

Answer Source

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>