[英]add and remove options from select box when other item selected
I have used the code (below) which was featured on jsfiddle. 我使用了jsfiddle中精选的代码(如下)。 The problem i have is that if i change the option value to be different from the text value, it then adds the value back into the text field on change. 我的问题是,如果我将选项值更改为与文本值不同,那么它将在更改时将值添加回文本字段中。
jQuery(function(){
jQuery('.selbox').change(function(){
var val = jQuery(this).val();
var sel = jQuery(this);
if(val != "")
{
if(sel.data("selected"))
{
var oldval = sel.data("selected");
sel
.siblings('select')
.append(jQuery('<option/>').attr("value", oldval).text(oldval));
}
sel
.data("selected", val)
.siblings('select')
.children('option[value=' + val + ']')
.remove();
}
else if(val == "")
{
if(sel.data("selected"))
{
var oldval = sel.data("selected");
sel
.removeData("selected")
.siblings('select')
.append(jQuery('<option/>').attr("value", oldval).text(oldval));
}
}
});
});
I am using code 我正在使用代码
<option value="1">text here</option>
Please see here for the original code http://jsfiddle.net/BUuZv/2/ 请在此处查看原始代码http://jsfiddle.net/BUuZv/2/
Instead of removing them and adding them, you could simply hide/show
them like this fiddle 除了删除并添加它们,您还可以像这样摆弄或 hide/show
它们
$(function() {
$('.selbox').change(function() {
var val = $(this).val();
var sel = $(this);
if (val != "") {
if (sel.data("selected")) {
var oldval = sel.data("selected");
sel.siblings('select').find('option[value="' + oldval + '"]').show()
}
sel.data("selected", val).siblings('select').children('option[value=' + val + ']').hide();
}
else {
if (sel.data("selected")) {
var oldval = sel.data("selected");
sel.removeData("selected").siblings('select').find('option[value="' + oldval + '"]').show()
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.