Add DIV’s with different ID’s using Jquery

Asked

Viewed 792 times

0

Hello,

I tried several tricks (unfortunately) but I can’t find a solution to my idea. I have an "app" that creates a to-do list, only I’d like to add to my list a different id for each div added within the div leading.

var main = function(){
  $('button').click(function(){
    var tarefa = $('input[name=tarefa]').val();
    var conferir = $('.item').text();
         if(tarefa==conferir){
       alert("Tarefa já foi adicionada!");
     }

//Adiciona um div com o id item dentro do div com classe lista-tarefa
  $('.lista-tarefa').append('<div id="item">' + tarefa + '</div>');
    $('input[name=tarefa]').val('');
  })
  $(document).on('click', '.item', function(){
    if (confirm("Deseja apagar?")){
    $(this).remove();
    }
  })
}

$(document).ready(main)

In the comment part he will always add a div with the same id, but I’d like to add with a different id so I can do a repeat validation when the user enters the task. In practice I would like to add a div with id="item1", id="item2", and so on.

3 answers

1

You can use the date of creation of div to ensure a unique id for div. To generate the id based on the date do the following:

var id = new Date().getTime();

With this you will ensure uniqueness in the ids generated avoiding conflicts.

After generating the id Just invite him into your div before adding to the page.

1

function guid() {
        return 'f' + (Math.random() * (1 << 30)).toString(16).replace('.', '');
}

In a project that I’m working on, I need to generate several components and I’m using this function to manage the ids. I found this function in a bibilioteca facebook.

What this function does is generate a random number that you can assign in your div.

Example:

var main = function(){
    $('button').click(function(){
        var tarefa = $('input[name=tarefa]').val();
        var conferir = $('.item').text();
        if(tarefa==conferir){
            alert("Tarefa já foi adicionada!");
        }

        //Adiciona um div com o id item dentro do div com classe lista-tarefa
        $('.lista-tarefa').append('<div id="'+ guid() +'">' + tarefa + '</div>');
        $('input[name=tarefa]').val('');
    })

    $(document).on('click', '.item', function(){
        if (confirm("Deseja apagar?")){
            $(this).remove();
        }
    })
}

$(document).ready(main)

0

You must set a counter and generate the id dynamically:

var contador = 0; // <<<=========== CONTADOR DECLARADO AQUI

var main = function(){
    $('button').click(function(){
        var tarefa = $('input[name=tarefa]').val();
        var conferir = $('.item').text();
        if(tarefa==conferir){
            alert("Tarefa já foi adicionada!");
        }

        // gera o id e incrementa o contador para não gerar id's iguais.
        var id = "item" + contador; // <<<==== ID DECLARADO AQUI
        contador++;

        // repare que utilizamos o id definido anteriormente:
        $('.lista-tarefa').append('<div id="' + id + '">' + tarefa + '</div>');
        $('input[name=tarefa]').val('');

        $("#" + id).on("click", function () {
            if ( confirm("Deseja apagar?") ) {
                $(this).remove();
            }
        });
    });

    $(document).on('click', '.item', function(){
        if (confirm("Deseja apagar?")){
            $(this).remove();
        }
    });
}

$(document).ready(main);

I believe you intend to also add the class item to the task created. Use:

  $('.lista-tarefa').append('<div id="' + id + '" class="item">' + tarefa + '</div>');
    $('input[name=tarefa]').val('');
  });

I hope I’ve helped.

  • Vinicius, I tried to use it in his own way but I failed to declare the variable counter, because when I execute the code he says that the variable does not exist. And if I start it with 1 or 0 it always adds the same number.

  • I didn’t need to add a class at the end, I was using classes for manipulation anyway. In the part where Voce puts the $("#" + id).on... Does not work uncaugth Referenceerror: id is not defined.

  • In my code the variable contador is declared and initialised, and id in its scope of use. I will highlight the statements of these variables in my code, as it probably lacked copy something to your code.

  • I removed the final snippet of the answer. Got confused hehehe.

Browser other questions tagged

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