Search code examples
javascripthtmljquerywebdom-manipulation

How to get unique value from dynamically create divs by using JQuery?


I am creating div inside div tag on button click, It is created and shown on UI , but I am unable to get the unique value inserted in dynamic created div. I always get the first value. Code sample:

<div id="row-list-outer"> </div>

Dynamically adding code sample, This code runs on each click

 $("#row-list-outer").append(` <div class="row g-3">
                     <div>                                  
                       <input type="text" id="salesPersonName" placeholder="Name">
                      </div>
                  </div>)

Now input element is created on click, but If I enter a value in 2nd row input, or 3rd row input etc. Then How I get those values in the same order as they are inserted. For example if the user enters in first row input, then it should be stored on index 0 in array, similarly, if user enters in 1 row, 2nd row, then it should be inserted on array at index 1, 2 respectively


Solution

  • You can try something like this:

    function addRow() {
      $("#row-list-outer").append(`<div class="row g-3">
                         <div>                                  
                           <input type="text" id="salesPersonName${$("input[id^=salesPersonName]").length + 1}" placeholder="Name">
                          </div>
                      </div>`)
    }
    
    $(document).on("change","input[id^=salesPersonName]",function() {
      var v = $("input[id^=salesPersonName]").map(function() {
        return $(this).val() || ""
      }).get();
      console.log(v)
    })
    

    Demo

    function addRow() {
      $("#row-list-outer").append(`<div class="row g-3">
                         <div>                                  
                           <input type="text" id="salesPersonName${$("input[id^=salesPersonName]").length + 1}" placeholder="Name">
                          </div>
                      </div>`)
    }
    
    $(document).on("change","input[id^=salesPersonName]",function() {
      var v = $("input[id^=salesPersonName]").map(function() {
        return $(this).val() || ""
      }).get();
      console.log(v)
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="row-list-outer"> </div>
    
    
    <button onclick="addRow()">addRow</button>