简体   繁体   中英

AJAX/Javascript In a Form and then submit it

I'm php developer starting to get heavier into ajax and I've come across a problem I am not sure how to solve.

I am creating a form on the fly like this:

function addSearchResult(label, tz) {
    var html = '';
    html += '<div>'
    html += '<form id="product-form" >';
    html += '<div class="clock">'
    html += '<div class="hour"></div>'
    html += '<div class="min"></div>'
    html += '<div class="sec"></div>'
    html += '<input type="text" id="label" name="Label" placeholder="Label">'
    html += '</div>'
    html += '<div class="city">GMT</div>'
    html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>'
    html += '</form>'
    html += '</div>'
    var insert = $(html);
    $('#search-results').append(insert.data('tz_offset', tz).find('.city').html(label).end());
}

And I am reading the form results like this:

$('#product-form').submit(function() {
    alert('OK');
    addProduct('Test Value', 'Test Produlct');
    $('input').blur();
    $('#add .cancel').click();
    this.reset();
    return false;
});

The problem is, it does not work. If I put the form directly in the html it works fine. But adding it through ajax, it will not pick up that the form exist.

How should I go about solving this problem?

Using the shortcut event handlers (eg submit() or click() ) only works for elements which are placed in the DOM on page load.

For dynamically added elements, you need to use delegate() , or on() for jQuery 1.7+. Try this:

< jQ 1.7

$('#search-results').delegate('#product-form', 'submit', function() {
    // rest of your code
});

jQ 1.7+

$('#search-results').on('submit', '#product-form', function() {
    // rest of your code
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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