I have a page with a list of li
elements, each called .section
. The page starts with just one section, but the user can add more with a click. Each section has a dropdown called .wip-location
and three input fields called .section-number
, .section-name
, and .section-description
. (The -number and -description inputs are irrelevant but I included them here just in case they are causing problems.)
Every time the dropdown is changed, I'd like the selected text to get filled into the .section-name
input.
This works the first time (when there is only one .section
, .wip-location
, and .section-name
on the page), but as soon as the user adds more .section
s, it appears that Jquery is unable to figure out which element to act upon, and no inputs are filled.
HTML
<li class="section">
<div class="form-group row">
<label class="col-sm-2 text-sm-right">Section Number</label>
<div class="col-sm-7">
<input class="section-number" type="number" step="0.01" min="1" />
</div>
<label class="col-sm-2 text-sm-right">Section Name</label>
<div class="col-sm-7">
<input class="section-name" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 text-sm-right">Section Description</label>
<div class="col-sm-7">
<textarea class="section-description" />
</div>
<label class="col-sm-2 text-sm-right">WIP Location</label>
<div class="col-sm-7">
@Html.DropDownListFor(m => m.WipLocation,
new SelectList(Model.WipLocations, "Key", "Value"),
"-- select --",
new { @class = "wip-location" })
</div>
</div>
</li>
jQuery
// Automatically add Wip Location choice to Section Name input
$('.wip-location').change(function () {
var $location = $('option:selected', $(this)).text();
var $section = $(this).closest('.section');
var $sectionName = $section.find('.section-name');
$sectionName.val($location);
});
As I said, when there is only one .section
and .wip-location
on the page, it works perfectly. I suspect jQuery gets confused when there are multiple .wip-location
s or something, but I'm not sure if that's really the problem or how to fix it.
Since it is dynamically added you could try to call the event like this:
$(document).on('change', '.wip-location', function(){/*...*/})