[英]JQuery creating unwanted option tag in select menu
I am having an issue involving a multiple
select
menu. 我遇到一个涉及
multiple
select
菜单的问题。 The user has the ability to select
multiple items from Selectbox A and add them to Selectbox B. I Use jQuery
to add the items to an array each time the add button is clicked
and populate Selectbox B using a foreach
loop
in php
and for the most part it is working fine. 用户可以从Selectbox A中
select
多个项目并将其添加到SelectboxB。每次clicked
添加按钮时,我都使用jQuery
将项目添加到数组中,并使用php
的foreach
loop
填充SelectboxB。部分工作正常。
However the issue is that when the user adds the first item to Selectbox A it adds the item but also an empty option
tag which I do not want. 但是问题是,当用户将第一个项目添加到选择框A时,它会添加该项目,而且还会添加一个我不想要的空
option
标签。 Is there anything I can do to resolve this? 有什么我可以解决的吗?
This is my HTML
code: 这是我的
HTML
代码:
<select multiple="multiple" id="active" name="activecontributors[]">
<option value="0"> </option>
</select>
This is my JQuery
code: 这是我的
JQuery
代码:
var drop2html = $("#active").html();
//ADD/REMOVE functionality for the contributors select boxes.
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
drop2html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
$("#active").html(drop2html);
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
drop2html = $('#active').html();
});
//on submit select all the options in active contributors...
$('#mainform').submit(function(){
$("#active option").attr("selected", "selected");
});
For some reason when the page loads it always shows the option
tag. 由于某些原因,页面加载时总是显示
option
标签。 I would like for my select box to show no option
tag if possible. 如果可能,我希望我的选择框不显示任何
option
标签。
its because of the empty option already present in that menu. 这是因为该菜单中已经存在空选项。
$('#compresult option:selected').each(function(){
drop2html = '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
})
try this for without appending to the string or 试试这个而不附加到字符串或
var drop2html = '';
store empty value to it. 向其存储空值。
You can use below code without drop2html
variable and get rid of your problem : 您可以使用不带
drop2html
变量的以下代码来摆脱问题:
$(function(){
//remove empty option from active
$('#active option').remove();
$('#addBtn').click(function (e) {//Adding
e.preventDefault();
$('#compresult option:selected').each(function(){
$('#active').append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>');
})
});
$('#removeBtn').click(function (e){//Removing
e.preventDefault();
$('#active option:selected').each(function(){
$('#active option:selected').remove();
})
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.