jQuery remove options from select box
html, javascript, jquery
Solution
Try this:
html
<div class="box">
</div>
<button class="add">Add</button>
js
$(".add").on("click", function(){
$select_box = '<div><select><option value="v1">Value 1</option><option value="v2">Value 2</option><option value="v3">Value 3</option></select></div>';
var ddl = $($select_box).children();
var a= $("select").val();
if(a!="")
$("option[value='" + a + "']").remove();
$('.box').append($select_box);
});
fiddle
Ok i change a bit, try this version please:
js
$(".add").on("click", function(){
$select_box = '<div><select><option value="v1">Value 1</option><option value="v2">Value 2</option><option value="v3">Value 3</option></select></div>';
var ddl = $($select_box).children();
var a= new Array();
var i=0;
$("select").each(function(){
a[i] = $(this).val();
i++;
});
if(a.length>0){
for(var j=0; j<a.length; j++){
$(ddl).find("option[value='"+a[j]+"']").remove();
}
}
$('.box').append(ddl);
});
fiddle
For your last request:
js
$(".add").on("click", function(){
$select_box = '<div><select onchange="ddlChange(this);"><option value="v1">Value 1</option><option value="v2">Value 2</option><option value="v3">Value 3</option></select></div>';
var ddl = $($select_box).children();
var a= new Array();
var i=0;
$("select").each(function(){
a[i] = $(this).val();
i++;
});
if(a.length>0){
for(var j=0; j<a.length; j++){
$(ddl).find("option[value='"+a[j]+"']").remove();
}
}
$('.box').append(ddl);
});
window.ddlChange = function(ddl){
var a= new Array();
var i=0;
$("select").each(function(){
a[i] = $(this).val();
i++;
});
if(a.length>1){
for(var j=0; j<a.length; j++){
$(ddl).find("option[value='"+a[j]+"']").remove();
}
}
$('.box').append(ddl);
};
fiddle
Problem
I want to add the same select box multiple times with jQuery. Here's the code I'm trying: ``` $(".add").on("click", function(){ $select_box = '<div><select><option value="v1">Value 1</option><option value="v2">Value 2</option><option value="v3">Value 3</option></select></div>'; $('.box').append($select_box); }); ``` Demo: http://jsfiddle.net/hC578/ The above code works fine. However, I want to check if an option value has been selected in any of the previous select box, it should not appear in the later select boxes. For example, if option 1 is selected in the first select box, and another select box is added, it should not list the option 1 in it. How this can be done?