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 >
<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
CodePudding user response:
You can try something like this:
function addRow() {
$("#row-list-outer").append(`<div >
<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 >
<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>
CodePudding user response:
You can try the following code: HTML:
<div id="row-list-outer"> </div>
<button>Change color</button>
Jquery:
$("button").click(function(e){
e.preventDefault();
$("#row-list-outer").append(` <div >
<div>
<input type="text"
data-id="${$('.salesPersonName').length 1}" placeholder="Name">
</div>
</div>`);
})
let colors = [];
$(document).on("change","input",function(e){
let i = $(this).data('id') - 1
colors[i] = $(this).val();
console.log(colors)
});