我有以下代码,根据另一个下拉列表的选择(Text Color
)创建动态下拉列表(Background Color
)
它按预期工作,并完美填充文本颜色下拉列表。
但是,当我提交表单时,textC
的值每次都是空白的。如果我为Text Color
创建一个简单的选择,我的表单提交正常,所有变量都可以在下一页通过POST获得。
对此代码的textC
值始终为空的任何想法?
var black = [
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];
var white = [
{display: "Black", value: "black" },
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" }];
var gray = [
{display: "Black", value: "black" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];
$("#parent_selection").change(function() {
var parent = $(this).val(); //get option value from parent
switch(parent){ //using switch compare selected option and populate child
case 'black':
list(black);
break;
case 'white':
list(white);
break;
case 'gray':
list(gray);
break;
default: //default child option is blank
$("#textC").html('');
break;
}
});
//function to populate child select box
function list(array_list)
{
$("#textC").html(""); //reset child options
$(array_list).each(function (i) { //populate child options
$("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
});
}
&#13;
<p><b>Background Color ?</b><br>
<select name="theme" id="parent_selection">
<option value="">-- Please Select --</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="gray">Gray</option>
</select>
<p><b>Text Color?</b><br>
<select name="textC" id="textC">
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
&#13;
答案 0 :(得分:1)
你可以试试这个:
//function to populate child select box
function list(array_list)
{
$("#textC").html(""); //reset child options
$(array_list).each(function (i) { //populate child options
$('<option>').val(array_list[i].value).text(array_list[i].display).appendTo('#textC');
});
}
答案 1 :(得分:0)
您可以使用select2
https://select2.github.io/
//set each item to id=value, text=display
var black = [
{text:"", id:""},
{text: "Gray", id: "gray" },
{text: "Warm Red", id: "red" },
{text: "White", id: "white" }];
//initialized select2 control.
$("#textC").select2({
data: black,
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
placeholder: "choose item",
selectOnClose: true,
closeOnSelect: true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="textC" name="textC" style="width:100%"></select>