I have a button that spawn a selector and a div, both with unique IDs. I'm trying to get the value from one of these unique appended selectors with a JQuery function. So far I can get the value from the selector option and show in the div, but it shows in every other div that was spawned. I want to show only in the div related to the selector.
$(document).on('click', '#createNewLayer', function () {
$('#mainSeparator').append(
'<div id="newLayer" class="newLayer"> <div class="form-row"> <div class="form-group col-md-6"> <select class="form-control mySelector" id="selector"> <option hidden disabled selected value>Select an option</option> <option>1</option> <option>2</option> <option>3</option><option>4</option> </select> </div></div><div class="newDiv"></div></div>'
);
});
$(document).on('change', '.mySelector', function () {
var str = $(this).find('option:selected').map(function () {
return $(this).text();
}).get().join('');
$('.newDiv').text(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mainSeparator">
<div id="newLayer" class="newLayer">
<div class="form-row">
<div class="form-group col-md-6">
<select class="form-control mySelector" id="selector">
<option hidden disabled selected value>Select an option</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</div>
<div class="newDiv"></div>
</div>
</div>
<button type="button" class="btn btn-primary" id="createNewLayer" style="margin-top: 20px;">New Layer</button>