简体   繁体   English

jQuery序列化不适用于动态元素

[英]JQuery serialize doesn't work on dynamic elements

I'm using the jQuery .serialize function and can't get it to serialize the this particular dyamic elements form on submit. 我正在使用jQuery .serialize函数,无法在提交时序列化此特定动态元素表单。 Note that I've tried the form on static and dynamic code and it worked fine. 请注意,我已经在静态和动态代码上尝试过该表单,并且效果很好。 But I can't find the bug in this code 但是我找不到这段代码中的错误

Here's my form code 这是我的表格代码

<%= form_tag({action: :show}, method: "post", id: "ajax-show") do %>
            <select id="xtime">
              <% (0..95).each do |min| %>
                  <option><%= Time.at(min*15*60).utc.strftime("%H:%M") %></option>
              <% end %>
            </select>
            <input id="xprice" value="12"/>
            <a href="#" id="price-add">add</a>

            <ul id="price-list">

            </ul>
            <hr/>
            <%= submit_tag("Submit") %>
        <% end %>

and here's my jQuery code 这是我的jQuery代码

    $("form#ajax-show").on('submit', function (e) {
        'use strict';
        e.preventDefault();
        console.debug($(this).serializeJSON());
    });
    $(document).on('click', '#price-add', function (e) {
        e.preventDefault();
        var t = '<input enabled checked type="checkbox" name="times[]" value="' + $('#xtime').val() + '"/>' + $('#xtime').val();
        var p = '<input enabled checked type="checkbox" name="prices[]" value="' + $('#xprice').val() + '"/>' + $('#xprice').val();
        $('#price-list').append('<li>time:  ' + t + '  .  price: ' + p + '  .  <a href="#" id="price-remove">remove</a></li>')
    });
    $(document).on('click', '#price-remove', function (e) {
        e.preventDefault();
        $(this).parent('li').remove();
    });

If I understood you correctly, this should help you: 如果我对您的理解正确,这应该可以帮助您:

$("form#ajax-show").on('submit', function (e) {
  'use strict';
  e.preventDefault();
  var formEmulation = $("<form/>").append($("#price-list"));
  console.log(JSON.stringify(formEmulation.serializeArray()));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM