How to properly submit a dynamically created form with JS/jQuery?

时光毁灭记忆、已成空白 提交于 2019-12-11 11:07:10

问题


HTML:

<button class="search" name="search">search</button>

Javascript:

$('button.search').live('click', function(event) {
    var newForm = jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    }));
    newForm.submit();
});

Fiddle: http://jsfiddle.net/YqGLH/90/

Expected behavior: when clicking on the search button, page should forward to google search. Works as expected in latest Chrome, Safari and Opera.

Does not work in latest FF and IE9. Clicking the button silently fails, no error messages, no forwarding happens.

What am I missing here?


回答1:


I don't have a reference to any particular specification to support the why, but I believe it will work if you append the new form to the page:

$('button.search').live('click', function(event) {
    jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    })).appendTo('body')
    .submit();
});

Note also that it would be a good idea not to keep using .live() in any new code, given that it has been removed from the latest version of jQuery. Instead use:

$(document).on('click', 'button.search', function() {    // in jQuery v 1.7+   
// or
$(document).delegate('button.search', 'click', function() {    // in jQuery v 1.4.3+

(Ideally specifying a parent element closer to the button rather than document.)




回答2:


It's also worth mentioning that you must add the form to the body element, not the document. Chrome is forgiving and will work when the form is just added to the document element, but IE and Firefox will need you to add it to the body element specifically.



来源:https://stackoverflow.com/questions/16521271/how-to-properly-submit-a-dynamically-created-form-with-js-jquery

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