Jquery 引导选择带值和选项以创建新值

Jquery 引导选择带值和选项以创建新值,jquery,twitter-bootstrap,select,Jquery,Twitter Bootstrap,Select,我想从数据库中选择一个带有预定义选项的选择字段,并允许用户从预定义选项中进行选择,或者在列表中没有合适的值时创建一个新值 我用的是bootstrap3 以及使用类似ajax的方法创建选择字段 /* * select product attributes on change of product type */ $("#producttypes").on('change',function() { var id = $(this).val(); $("#pro

我想从数据库中选择一个带有预定义选项的选择字段,并允许用户从预定义选项中进行选择,或者在列表中没有合适的值时创建一个新值

我用的是bootstrap3

以及使用类似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);
         }
      });
    }
  });

简而言之,我需要输入type=text和选择标记的组合,在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">

现在我想,它回答了你的问题。

在你的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">

现在我想,它回答了你的问题。

试试这样的方法。我试过这样做,但onchange无法处理jQuery生成的代码。如果选择字段是在htmltry中预定义的(类似于这样),同样可以正常工作。我尝试过这样做,但onchange无法处理jQuery生成的代码。如果选择字段是在html中预定义的,同样可以正常工作