Reputation: 3386
I have a view that contains two @Html.DropDownListFor
helpers:
<div class="editor-field">
@Html.DropDownListFor(model => model.Employee, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl1"})
@Html.ValidationMessageFor(model => model.Employee)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Employee2, (IEnumerable<SelectListItem>)ViewBag.emps, "--Select--", new { style = "width:150px", id = "ddl2"})
@Html.ValidationMessageFor(model => model.Employee2)
</div>
They are populated like this:
public ActionResult Create()
{
List<Employees> emps = new List<Employees>();
emps.Add(new Employees { Id = 0, Name = "Michael Jordan" });
emps.Add(new Employees { Id = 1, Name = "Magic Johnson" });
emps.Add(new Employees { Id = 2, Name = "Larry Bird" });
var items = emps.Select(i => new SelectListItem
{
Value= i.Id.ToString(),
Text =i.Name
});
ViewBag.emps = items;
return View();
}
How can I remove the selected item of the first DDL from the second DDL? I managed to get the selected item using jQuery like this:
<script type="text/javascript">
$(function () {
$("#ddl1").change(function () {
alert($("#ddl1").val());
});
});
</script>
However, I couldn't find a way to use it for my purpose.
Upvotes: 4
Views: 2216
Reputation: 17288
Something like this must work for you:
$(function(){
var lists = $('#ddl1, #ddl2');
lists.change(function(){
var elm = $(this);
lists.find('option').show();
var option = lists.not('#' + this.id)
.find('option[value="' + elm.val() +'"]').hide();
if(option.is(':selected'))
{
var select = option.closest('select');
select.val(select.find('option:visible:first').val());
}
});
});
Link for demo: jsfiddle.net
Added: Posted solution have problems with IE, alternative way is use disabled attribute: jsfiddle.net/cxZ2H/1/
Upvotes: 3
Reputation: 15365
This is definitely a client-side scripting problem as opposed to a server-side ASP.NET MVC problem.
Here is my advice:
select
.Here's a JSFiddle: http://jsfiddle.net/Fsf7g/1/
Upvotes: 2