Search code examples
javascriptjquerydynamicdrop-down-menuunique-id

On button click create dynamic drop down lists with unique id's in JavaScript


I want to create multiple dynamic drop down lists on click of a button.. Each added drop down list should have a unique I'd.

I have a piece of code which creates multiple drop down list but I don't know how to add code for creating unique IDs for ddls..

Here is my code which creates ddls:

<div class="col-md-4">
<div class="form-group" id="containerOWL">
// I want to add dynamic drop down list here
</div>
</div>

<div class="row" style="margin-bottom: 32px;">
<a class="btn btn-primary" onclick="OW_LO_LW()" style="margin: 0 0 0 15px;">+ Add OWL/LO/LW</a>
</div>

function OW_LO_LW() {
var drop_list = '<select class="form-control">';
drop_list += '<option selected disabled >Select</option>';
drop_list += '<option >FL</option>';
drop_list += '<option >GA</option>';
drop_list += '<option >AL</option>';
drop_list += '</select>';
$("#containerOWL").append(drop_list);
}

Thank you ☺️


Solution

  • You can add a data attribute to containerOWL like this data-number=0

    Now on function call you can simply get that number and increase it by one and give that value to that select id. And finally increase that data attribute value.

    complete code:

    function OW_LO_LW() {
        containerOWL = $("#containerOWL")
    
        const currValue = containerOWL.data("number")
        const nextValue = currValue + 1
    
        var drop_list = `<select id="${nextValue}" class="form-control">`;
        drop_list += '<option selected disabled >Select</option>';
        drop_list += '<option >FL</option>';
        drop_list += '<option >GA</option>';
        drop_list += '<option >AL</option>';
        drop_list += '</select>';
        containerOWL.append(drop_list);
    
        containerOWL.data("number", nextValue)
    }