[英]MVC Duplicating Drop-Down list on selection
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 使用以下JavaScript代码
<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 和剃刀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.). 我可以自己制作第一个列表克隆,但是如何从函数q返回x以便它可以由其自己的函数使用(当在Foo1中选择了项,然后在Foo2中选择了项时,函数q需要触发) 。
(Sorry if this doesn't make sense, I am not sure how to word it. I am very new to coding). (很抱歉,如果这没有意义,我不确定该怎么写。我对编码非常陌生)。 Thanks.
谢谢。
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. 我不记得Html.DropDownList签名,所以我创建了没有它的简单jsfiddle 。 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. 现在,如果不是最后一次更改,它不会添加额外的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.