Reputation: 3
I am trying to make a page where the user selects an item in a drop-down list, which then will create a duplicate drop-down list. The last drop-down list always needs to create a new one once an item is selected.
Using the following javascript code
<script type="text/javascript">
$(document).ready(function () {
$(function listselect() {
if (x == null) {
var x = 1;
}
//need to increment x after the completion of the following funciton so the function will trigger on different drop-down lists
$('#FooId' + x).change(function q() {
$('#FooId' + x).clone().attr('id', 'FooId' + (++x)).attr('name', 'Selected').insertAfter('#FooId' + (x - 1))
//return x;
});
//return x;
});
});
</script>
and the razor html
<div class ="container">
<div class="label">
@Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
@Html.DropDownList("FooId", Nothing, "--Select--", New With {.Name = "Selected", .Id = "FooId" & "1"})
//@*@Html.ValidationMessageFor(Function(model) model.Foo)*@
</div>
</div>
I am able to make the first list clone itself, but how do you return x from function q so that it can be used by its own function (Function q needs to trigger when an item is selected in Foo1, then Foo2, etc.).
(Sorry if this doesn't make sense, I am not sure how to word it. I am very new to coding). Thanks.
Upvotes: 0
Views: 786
Reputation: 8110
If I got you right, you don't need most of your code. And it's easier to use classes here. Just do it like this:
$(document).ready(function () {
$('.foo').on('change', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
});
And your markup part should be like this:
<div class ="container">
<div class="label">
@Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
@Html.DropDownList("FooId", Nothing, "--Select--", new {name = "Selected", @class = "foo" })
</div>
</div>
I don't remember Html.DropDownList signature so I created simple jsfiddle without it. I hope this is what you needed.
I've corrected my fiddle as follows:
$(document).on('change', '.foo:last', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
Now it doesn't add extra selects if it's not the last select that was changed.
Upvotes: 2