Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add ascending numbers to ID

I have a form that generates divs. I have applied a base ID to each div but I need to add numbers to them to differentiate between them.

I have read up on Index and looked at other example but I can't get it to work here, it seemed to throw a wobbly when I put the num variable in. Anyway I took out the code that was breaking it.

Here is the fiddle, http://jsfiddle.net/clintongreen/BMX4J/13/

Thanks

like image 896
Clinton Green Avatar asked Sep 14 '25 03:09

Clinton Green


2 Answers

val() is not correct here. val() is for input elements.

When you do:

var newDiv = $('<div id="toggleshow" ......

Change it to:

var newDiv = $('<div id="toggleshow_' + num++ + '"

And do var num = 0; outside of the function.

like image 150
Ariel Avatar answered Sep 16 '25 18:09

Ariel


It sounds like you want to make every id in the created div unique by adding a counter of sorts to a base id. If so the easiest way to do this two use two functions. Have the counter be in the outer function and let the inner function be the click handler which captures the counter and reuses it.

$(".add_menu_item").click((function() {
  var id = 0;
  return function () {
    var value = $(this).prev().val();
    if (value.length) {
      var newDiv = $('<div id="toggleshow" class="div_menu_button"></div>');
      var showDiv = $('<div id="show"' + id + '">Bob Lawbob</div>');
      $('#created_buttons_list').append(newDiv.val(value).text(value));
      newDiv.wrap("<li></li>");
      newDiv.after(showDiv);
      id++;
    }
  }
})());

Fiddle: http://jsfiddle.net/BMX4J/17/

like image 25
JaredPar Avatar answered Sep 16 '25 18:09

JaredPar