我想要一个带有数据库预定义选项的选择字段,并允许用户从预定义选项中进行选择,或者如果列表中没有合适的值,则创建一个新值。
我使用的是Bootstrap 3
并使用ajax创建选择字段,如
/*
* select product attributes on change of product type
*/
$("#producttypes").on('change',function() {
var id = $(this).val();
$("#product_attributes").html('');
if (id) {
var dataString = 'id='+ id;
$.ajax({
dataType:'json',
type: "POST",
url: '/products/ajax-get-product-attribute-types' ,
data: dataString,
cache: false,
success: function(data) {
var i = 0;
$.each(data, function(key, value) {
var message = '<div class="form-group">' +
'<label>'+value['title']+'</label>' +
'<input type="hidden" name="product_attribute_type_title[]" value="'+value['value']+'" />' +
'<select name="product_attribute_value[]" class="form-control select2" style="width:100%">';
$.each(value['product_attributes'], function(a, b) {
message += '<option value="'+b['value']+'">'+b['value']+'</option>';
})
message += '</select>' +
'</div>';
$('#product_attributes').append(message);
i = i+1;
});
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
简而言之,我想要input type="text"
和select
标签的组合
答案 0 :(得分:0)
/*
* select product attributes on change of product type
*/
$("#producttypes").on('change',function() {
var id = $(this).val();
$("#product_attributes").html('');
if (id) {
var dataString = 'id='+ id;
$.ajax({
dataType:'json',
type: "POST",
url: '/products/ajax-get-product-attribute-types' ,
data: dataString,
cache: false,
success: function(data) {
var i = 0;
$.each(data, function(key, value) {
var message = '<div class="form-group">' +
'<label>'+value['title']+'</label>' +
'<input type="hidden" name="product_attribute_type_title[]" style="display:none;" class="product_attribute_type_title" value="'+value['value']+'" />' +
'<select name="product_attribute_value[]" class="form-control select2" style="width:100%">';
$.each(value['product_attributes'], function(a, b) {
message += '<option value="'+b['value']+'">'+b['value']+'</option>';
})
message += '<option value="others">Others</option></select>' +
'</div>';
$('#product_attributes').append(message);
// change events
$(".select2").on("change",function(){
if($(this).val() == "others")
{$(this).find(".product_attribute_type_title").css("display","none");
$(this).find(".product_attribute_type_title").focus();
}});
i = i+1;
});
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
答案 1 :(得分:0)
在你的ajax调用之后添加它
$(".select2").append('<option value="">Other</option>');
$(".select2").on("change", function(){
if(this.value=="")
$(".othertxt").removeClass("hidden").focus();
else
$(".othertxt").addClass("hidden");
});
并在html中添加
<input type="text" class="hidden othertxt">
现在我猜,它回答了你的问题。