I have a server-side generated list of options like the following,
<select id="chosen">
<option value="1">select 1</option>
<option value="2">select 1</option>
<option value="3">select 1</option>
<option value="4">select 1</option>
<option value="5">select 1</option>
</select>
based on the option selected, the data will be pulled from the server and append to a table (row)
What I want to achieve is, when I select the item from the list of options (using onChange) I want to remove that selected item from the list (so that I do not repeat selecting the same item again by mistake)
I have compiled the following onChange script
$("#chosen").change(function() {
var data = "";
var val = $("#chosen option:selected").val();
$.ajax({
type:"GET",
url : "pull_cust_inv.php",
data : "invId="+$( "#chosen option:selected" ).val(),
async: false,
success : function(data) {
$("#inv_list").append(data);
//$("#chosen option:selected").remove();
},
error: function() {
alert('Error occured');
}
});
// REMOVE SELECTED OPTION
$("#chosen option[value="+val+"]").remove();
});
However, for some weird reason, the option still appears in the list (does not remove itself) but when I select it for the second time it does not get selected.
can someone advise what is wrong in my code?
I figured the answer myself. I am using the "chosen" jquery plugin for the select dropdown list, therefore the traditional method (below) will not work
$("#chosen option[value="+val+"]").remove();
Solution if anyone happens to use the technique i've implemented using the "chosen" (jquery Plugin) the correct way to remove a selected option is to write the following lines.
$("#chosen option[value="+val+"]").remove();
$("#chosen").trigger("chosen:updated");
what is means is, once your "remove" the option element you will have to trigger the "chosen:updated" method.
This only implies if you are using the chosen Jquery UI plugin.
Hope it helps someone :)