JQuery Ajax Form and Dynamically created form elements not submitting

故事扮演 提交于 2019-12-04 03:59:56

问题


I'm writing a form that has some text input elements loaded dynamically when a select list is changed.

The problem is that when I submit the form those elements are not sent in the data that is posted to the server.

What do I need to do to get those dynamically created elements "into" the form to be submitted?

The code is something like this:

$("#my_select_id").change(function() {
    $.ajax({
        type: "GET",
        url: "some-url/" + $("#played_number_game_id").children("option:selected").val(),
        async: false, 
        dataType: "html",
        error: function(XMLHttpRequest, status, errorThrown) {
            alert("oh no!");
            alert(status);
        },
        success: function (data, status) {
            $("#parent-element").html("");
            $("#parent-element").append(data);
        },
        complete: function() {
        }
    });

    $("#my_form_submit").click(function() {
        $("#my-form").ajaxSubmit({ clearForm: true }); 
        return false;
    });
});

The html returned by the ajax call is:

<input id="my-form_e_1" class="number-input" type="text"/>
<input id="my-form_e_2" class="number-input" type="text"/>

And if I use firebug to look at the page after calling the ajax method the dynamically loaded html is right in the hierarchy where it should be...i.e. it's in the form.

But when I click the submit button only the elements of the form that existed before the ajax call get posted.

Any ideas?


回答1:


Your problem seems to be that the dynamically added input elements do not have name attributes. Input elements require name attributes if you want their values to be included in the submitted data.




回答2:


It's pretty simple, just append the form element to the body tag and set its style to 'display:none'



来源:https://stackoverflow.com/questions/1898508/jquery-ajax-form-and-dynamically-created-form-elements-not-submitting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!