Dynamic ID with Jquery

Asked

Viewed 716 times

3

I have a function that creates a span with id, but I need that id to be generated dynamically example id="span1" /id="span2", as I do this?

$("#lista").append("<span id='span'><br> " + label + " - R$" + valor + "</span>" );
  • 3

    Have you tried creating a variable with the value, concatenate it next to the id and increment it with each added element?

  • 1

    Wouldn’t it be better to use a class ? In most cases it solves the problem without having to do this kind of thing.

2 answers

2


Count how many spans containing the id which starts with "span" and disappears with +1. This will create a new id sequential:

var label = "label";
var valor = "10,00";

function addSpan(){
   var span_id = $("#lista span[id^='span']").length+1; // novo id
   $("#lista").append("<span id='span" + span_id + "'><br> " + label + " - R$" + valor + " - id: span"+ span_id +"</span>" );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lista"></div>
<button onclick="addSpan()">Adicionar span</button>

1

The easiest way I see it is:

var x = 0;
$('O QUE VOCE ESCOLHER').click(function(){
    x++;
$("#lista").append(`<span id='span${x}'><br>  ${label} - R$ ${valor} "</span>` );
});

Instead of using single quotes ' or double quotes "" put the crase, and for each variable you put inside ${} hence the js already understand that what is inside ${} is a variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.