javascript – 表单提交时,动态注入的表单字段不会被提交

<%= simple_form_for @product, method: :post, url: save_item_path do |f| %>
    <tr>
        <td>
            Category
        </td>
        <td>
            <%= f.input :category_id, collection: Category.all, label: false, prompt: 'Select your category', required: true ,required: true %>
        </td>
    </tr>

    <div class="row " style="height:100px;width:100%">
        <div class="col-md-5 sub-cat-dropdown">
            <select class="select required sub-cat" required="required" name="product[sub_id]"><option value="">Select your sub category</option><option value="15">Bottle</option><option value="16">Charger</option></select>
        </div>
    </div>

    <div class="row">
        <div class="col-md-3 col-md-offset-5">
            <%= f.submit :submit %>
        </div>
    </div> 

<% end %>       

表格将与所有需要的参数一起提交.这里是参数

{"utf8"=>"✓", "authenticity_token"=>"4gY7lWgSqo6j4UoZ78iv1nsaMq9TUXLXE2oQzlqqyh3I3oED3CxwM04cB1n5P+Nz81O3Vvk+/NDPxixNey/J9Q==", "product"=>{"name"=>"vamsi", "price"=>"456", "availability"=>"true", "about"=>"aerg", "ref"=>"456", "texture"=>"rdgg", "shipping"=>"ewataewrg", "category_id"=>"13", "notes"=>"feartg", "packaging"=>"wer5tyy", "sub_id"=>"15"}, "commit"=>"submit", "controller"=>"items", "action"=>"create"} 

在上面的params哈希中,你可以提交sub_id.

但是,必须根据主类别的选择动态生成子类别下拉列表.

所以sub-cat-dropdown div就像这样清空了

<div class="row " style="height:100px;width:100%">
        <div class="col-md-5 sub-cat-dropdown">

        </div>
</div>

我想点击主要类别下拉列表,在子猫下拉列表中注入一个选择标记

这是我写的代码

$(document).ready(function(){

    //this function is supposed to create a dropdown of sub category
    //based on the main category dropdown

    $('#product_category_id').on('change', function(){

        var values = [];
        var inner_contents = [];

        if(this.value === undefined){
            return;
        }else{
            $main_category = this.value;
            $main_category_length = $cat_obj[$main_category].length;
            for (var i=0;i<$main_category_length;i++){
                values.push($cat_obj[$main_category][i].id);
                inner_contents.push($cat_obj[$main_category][i].name);
            }

            $('.sub-cat-dropdown').empty();
            inject_sub_category(values, inner_contents);
        }

    });



    // this function injects a dropdown of sub categories, just below the categories ... 


    function inject_sub_category(value_array, inner_html_array){

        var select = document.createElement("select");
        select.setAttribute("class","select required sub-cat");
        select.setAttribute("required","required");
        select.setAttribute("name","sub_id");

        // the above will create this 
        //  <select class ="select required form-control"
        //                  required = "required"       
        //                  name = "product[sub_id]"
        //                  id = "sub_cat_id"> 
        //  </select>               

        $('.sub-cat-dropdown').append(select);  


        // setting the default option 

        var default_option = document.createElement("option");
        default_option.setAttribute("value","")
        default_option.innerHTML = default_option.innerHTML + "Select your sub category";
        select.appendChild(default_option);
        // injecting <option value> Select your category </option> under select tag

        // creating options of subcategories, and injecting under the select element as children
        for(var i = 0 ; i< value_array.length ; i++){
            var option_element = document.createElement("option");
            option_element.setAttribute("value",value_array[i]);
            option_element.innerHTML = option_element.innerHTML + inner_html_array[i];
            select.appendChild(option_element)
        }



    }


        // this is supposed to read the json data of the categories and sub categories

        $.ajax({
        url: "http://localhost:3000/categories_api/show",
        type: 'GET',
        dataType: 'json', 
        success: function(res) {
                $cat_obj = res;
        }
    });

});

上面代码的作用是它应该在子猫下拉列表中插入一个选择下拉列表

插入的选择标记看起来像这样,从浏览器复制

 <div class="col-md-5 sub-cat-dropdown" style="-webkit-user-select: text;"><select class="select required sub-cat" required="required" name="product[sub_id]"><option value="">Select your sub category</option><option value="15">Bottle</option><option value="16">Charger</option></select></div>

但是,当表单提交发生时,params没有sub_id

{"utf8"=>"✓", "authenticity_token"=>"zUVF55KdvQ4l8nBjtlIcofqHECgd3/pIi7U97cF0xbrnnf9xJqNns8gPPSOgpVAEcs6V0bewdE9XGQFu4PHGUg==", "product"=>{"name"=>"jdkrfb", "price"=>"89", "availability"=>"true", "about"=>"sfukb", "ref"=>"78678", "texture"=>"jkdfbjkrbg", "shipping"=>"jkdfsk", "category_id"=>"12", "notes"=>"jhhdfvbj", "packaging"=>"sajkf"}, "commit"=>"submit", "controller"=>"items", "action"=>"create"}

我在过去几个小时内遇到过这个问题,我们将非常感谢您的帮助.

我的观察:

ajax调用和生成select标记的函数没有问题.我可以看到DOM具有生成的选择标记,并且是子猫下拉列表的子项.

静态选择标记的sub_id正在提交,但对于动态标记,则不是这样.它没有提交

最佳答案 在javascript中,即使您在DOM中看到它们,也无法在动态创建的元素上添加事件侦听器.这就是为什么动态创建的选择选项输入将在DOM中但不包含在表单数据中.尝试将选择输入保持为静态并使其中的选项保持动态.

<div class="row " style="height:100px;width:100%">
 <div class="col-md-5 sub-cat-dropdown">
  <select class="select required form-control" required="required" name="product[sub_id]" id="sub_cat_id">
  </select>    
 </div>
</div>

代替

<div class="row " style="height:100px;width:100%">
 <div class="col-md-5 sub-cat-dropdown">
 </div>
</div>

然后通过javascript更改选择输入内的选项 –

function inject_sub_category(value_array, inner_html_array){

    // setting the default option 

    var default_option = document.createElement("option");
    default_option.setAttribute("value","")
    default_option.innerHTML = default_option.innerHTML + "Select your sub category";
    $("#sub_cat_id").append(default_option);
    // injecting <option value> Select your category </option> under select tag

    // creating options of subcategories, and injecting under the select element as children
    for(var i = 0 ; i< value_array.length ; i++){
        var option_element = document.createElement("option");
        option_element.setAttribute("value",value_array[i]);
        option_element.innerHTML = option_element.innerHTML + inner_html_array[i];
        $("#sub_cat_id").append(option_element)
    }

}

还有另一种使用event delegation的方法.

点赞