我正在使用C#和SQL Server 2005开发ASP .Net MVC 3应用程序。
在视图中,我有一个DropDownList,一个按钮。
每次点击按钮时,如何从DropDownList中删除项目。
我尝试使用javascript,但我认为这不起作用,因为当我点击按钮时,没有任何反应。
这是代码:
<%:Html.Label("Poste :")%>
<%:Html.DropDownListFor(
model => model.SelectedPoste,
Model.PostesItems,
new { @id = "poste" })%>
<div>
<input type="submit"
value="Enregistrer"
id="btnSave"
onclick="remove()" />
</div>
<script type="text/javascript">
function remove() {
var rm = document.getElementById('btnSave');
var poste = document.getElementById('poste');
poste.removeItem();
}
</script>
答案 0 :(得分:2)
使用 vanilla JavaScript ,您可以:
<script type="text/javascript">
function removeOption() {
var posteElement = document.getElementById('poste');
var currentIndex = posteElement.selectedIndex;
posteElement.removeChild(posteElement[currentIndex]);
return false;
}
</script>
这就是你所需要的一切。另外,请确保将您的功能重命名为remove()
以外的任何其他内容:
<input type="submit"
value="Enregistrer"
id="btnSave"
onclick="removeOption()" />
看看这个(不是很好inline-fiddle)。
但是我强烈建议至少要查看一个像jquery这样的库(这比使用vanilla.js容易得多)。看看安德烈的答案。
答案 1 :(得分:2)
生成的HTML将为select元素提供ID“SelectedPoste”,而不是“poste”,因为您尝试设置。
使用remove
删除项目。
将您的javascript更改为:
var poste = document.getElementById('SelectedPoste');
poste.remove(poste.selectedIndex);
修改:为select生成的HTML将为:
<select id="poste" name="SelectedPoste">...</select>
这两行中的任何一行都将获得这些元素:
var poste = document.getElementById('poste');
或
var poste = document.getElementById('SelectedPoste');
(IE10中的Atleast)
然后从列表中删除所选项目,执行:
poste.remove(poste.selectedIndex);
这不会删除按钮:)
编辑2:与Dimitar的回答一样,您需要将您的函数名称从remove
更改为其他名称。
完成上述操作后,我上面的代码可以在IE和Chrome中使用。
答案 2 :(得分:2)
使用 jQuery
<select id="poste">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<input type="button" id="btnSave" value="Remove current item" />
<script type="text/javascript">
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
return false;
});
});
</script>
编辑:使用jQuery绑定click事件
答案 3 :(得分:2)
试试这个:
$("#poste option[value='X']").each(function() {
$(this).remove();
});
或者更简洁,这也会起作用:
$("#poste option[value='X']").remove();
示例:
$("#btnSave").click(function(){
$("#poste option[value='X']").remove();
});
请记住使用 JQuery :)