c# - If else condition on dropdown list on MVC -
i have 2 dropdown list on web application. populated data of 2 dropdown comes database. contain same data.
what want if 1 of list selected on first dropdown, should not available on second dropdown anymore.
i have following razor syntax:
@html.dropdownlistfor(model => model.questions1, (selectlist)viewdata["questions"], "select>>", new { id = "questions1", name = "questions1"}) @html.dropdownlistfor(model => model.questions2, (selectlist)viewdata["questions"], "select>>", new { id = "questions2", name = "questions2"})
the questions came model retrieve database.
thanks in advance!
in order accomplish this, need store pool of options in javascript object. then, in 'onchange' event each drop-down, re-build options in other drop-down, excluding 1 chosen. here example using jquery:
// build javascript array of select names/values var options = new array(); $('#questions1 option').each(function() { $this = $(this); options.push({ name: $this.text(), value: $this.val() }); }); // create function re-building select minus chosen option var rebuildselect = function($seloption, $select) { $previouslyselected = $select.find(':selected'); $select.empty(); (var = 0; < options.length; i++) { var opt = options[i]; if (opt.value != $seloption.val()) { if ($previouslyselected.val() == opt.value) { $select.append('<option value="' + opt.value + '" selected="selected">' + opt.name + '</option>'); } else { $select.append('<option value="' + opt.value + '">' + opt.name + '</option>'); } } } } // wire event handlers var $questions1 = $('#questions1'); var $questions2 = $('#questions2'); $questions1.change(function() { rebuildselect($(this), $questions2); }); $questions2.change(function() { rebuildselect($(this), $questions1); }); // go ahead , run function on each box remove default entries other box rebuildselect($questions1.find(':selected'), $questions2); rebuildselect($questions2.find(':selected'), $questions1);
Comments
Post a Comment