In a form I need to dynamically add (and then remove) some fields (0 to n) from a select.
Every item should be removed from the list after being added so it can't be selected twice.
For example I have a select like this:
<select name="list">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
And I want to add a new field in my form that shows A and D and stores their values so I can get it through a POST. Then if I click on the select, there will be just B and C.
Can you help me?
What type of fields do you want? Input type text? If so:
$("[name=list]").on("change", function (e) {
var val = $(this).val();
if (val.length > 0) {
$(this).find("option:selected").remove();
$("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
}
});
check out the fiddle https://jsfiddle.net/etoysp7b/1/
i guess you are looking for this,
$("select[name='list']").on('change',function(){
var b=$(this).val();
if(b!=0){
$("#s1").append("<input type='text' name='newname"+b+"' value='"+$(this).find("option:selected").text()+"'/>");
$(this).find("option[value='"+b+"']").remove();
}
});
AND
<form id="s1">
<select name="list">
<option value="0">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</form>
you can try these options as well : 1. http://www.virtuosoft.eu/code/bootstrap-duallistbox/ 2. https://www.jqwidgets.com/jquery-widgets-demo/demos/jqxlistbox/index.htm#demos/jqxlistbox/dragdrop.htm