javascript
  • ajax
  • jquery
  • 2012-02-19 48 views 0 likes 
    0

    在javascript中,我創建多個表單和輸入到HTML我們AJAX/JS這樣的:AJAX/JavaScript的獲取提交的表單數據

    這些形式
    function addProduct(product) { 
            var html = ''; 
            html += '<div>' 
            html += '<form id="product-form">'; 
            html += '<div class="city">'+product['product_name']+'</div>' 
            html += '<div class="state">'+product['product_price']+'</div>' 
            html += '<input type="hidden" name="product_id" value="'+product['product_id']+'" id="product_id" >' 
            html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>' 
            html += '</form>' 
            html += '</div>' 
            var insert = $(html); 
            $('#main').append(html); 
           } 
    

    倍數與不同product_ids創建。我遇到的問題是獲取這種形式的價值。我能夠正確識別已提交的表單,但我無法確定輸入中的product_id。到目前爲止,我有這樣的:

    $('#main').on('submit', '#product-form', function() { 
    
            var product_id = $('?????').val() 
    
           }); 
    

    如何從提交的表單中獲取產品ID和其他相關數據?

    回答

    2

    使用類而不是id作爲表單,並使用submit按鈕代替「a tag」 ,然後讓你的提交功能像這樣

    $('.form_class').on('submit', function(e){ 
        e.preventDefault(); 
        var form = $(this); 
        var formUrl=form.attr('action'); 
        var product_id = $('#product_id', form).val(); 
    
        $.ajax({ 
         type: "POST", 
         url: formUrl, 
         data: product_id, // or use form.serialize(); 
         success: function(data){ 
          // code goes here; 
         }, 
         error:function (xhr, ajaxOptions, thrownError){ 
          // code goes here; 
         } 
        }); 
    }); 
    
    0
    $(this).find('.city').text(); 
    

    1

    可以提供上下文對jQuery $()功能:

    var product_id = $('input[name=product_id]', this).val(); 
    

    'input...'選擇將僅適用於內的第二個參數的情況下,在這種情況下this,其中this將由jQuery設置爲submit處理程序中的當前表單元素。

    或者你可以在它第一次,然後.find()元素選擇當前形式:

    var product_id = $(this).find('input[name=product_id]').val(); 
    

    請注意,我選擇的名字輸入,因爲雖然你已經給該元素的屬性id是不有效地將相同的id分配給多個元素。

    0

    簡短的回答是:

    $('#main').on('submit', '#product-form', function() { 
        var product_id = $(this).children('input[name=product_id]').val(); 
    }); 
    

    但我可以看到你的功能的問題。實際上,多次調用addProduct(...)將最終導致DOM無效,因爲您將擁有更多具有相同ID的元素(product-form,product_idview-product-button)。更好地審查它背後的整個想法...

    0

    首先,你不能創建具有相同ID的多個元素。使用類。 您的javascript中有很多id,但對於表單,它將爲: html += '<form class="product-form">';表單聲明和$('#main').on('submit', '.product-form', function() {捕捉事件。

    然後,當你發現一個事件時,this將引用當前事件目標。您可以使用以下命令檢索產品的值:$('input [name = product_id]',this)[0] .value

    相關問題