Question

I want to give the elements ids on the in JQuery when a button is clicked but as we all know, two elements should not have the same id. So I am creating an array of all the current ID's and checking to see if the next calculated id already exists. For some reason, it is not working as expected.

I want it to go into a loop until the id finds a number that is not already used. So in the code below, it counts 3 <li> and assigns the next element an id of 4, however, an element with that Id already exists so it should appear in the array and go into the loop to add 1 to the number until it finds a number that does not exist in the array. Any and all help is appreciated! Here is a fiddle.

JQuery:

$(document).ready(function () {
   $(".addParent").click(function () {

       var IDs = $("#list > li").map(function () {
           return this.id;
       }).get();

       var num = ($("#list").children().length) + 1;

       while (jQuery.inArray(num, IDs) != -1) {
           num++;
      }

       $("#list").append("<li id='" + num + "'><textarea class='inputBelief' rows='1' cols='50'>id is " + num + "</textarea></li>");

       return false;
   });
});

HTML:

<ol id="list">
    <li id='1'>
        <textarea class='inputBelief' rows='1' cols='50'>id is 1</textarea>
    </li>
    <li id='2'>
        <textarea class='inputBelief' rows='1' cols='50'>id is 2</textarea>
    </li>
    <li id='4'>
        <textarea class='inputBelief' rows='1' cols='50'>id is 4</textarea>
    </li>
</ol>
<a class="addParent" href="#">add line</a>
Was it helpful?

Solution

The issue is that IDs is array of strings not numbers, so inArray never works as you expect, because you are trying to find a number in array of strings. Try to change map method to this:

var IDs = $("#list li[id]").map(function () {
    return +this.id;
}).get();

Demo: http://jsfiddle.net/RmrXq/2/

OTHER TIPS

in the map function do

return parseInt($(this).prop('id'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top