2012-07-04 24 views
0

我在單個頁面上有一系列表單。我試圖抓住被提交的特定表單的id,並使用該確切的值作爲div的名稱來插入一些html。該div已經以該名稱存在。獲取表單ID,然後將其用作div名稱

下面是代碼:

$(function() { 
    $('.allforms').submit(function (ev) { 
     Var myID = $(obj).attr("id"); 
     esv.preventDefault(); 
     $.ajax({ 
      url: "/update", 
      data: $(this).serialize(), 
      dataType: "html", 
      success: function (data) { 
       $(myID).html(data); 
      } 
     }); 
    }); 
}); 

當我給的div相同名稱的數據被正確返回,但只顯示在第一個div,所以我知道在服務器端工作。我剛剛開始使用Jquery。

+0

發佈examp le你的html – ice

回答

0

改變這些:

Var myID = $(obj).attr("id"); // 'var' keyword should be lowercase 
esv.preventDefault(); // you are passing event object as `ev` not `esv` 

到:

var myID = $(this).attr("id"); // 'this' refers to the current form 
ev.preventDefault(); 
0
var myID = $(this).attr("id"); 

這將表格交回的ID

0

使用

$(function() { 
    $('.allforms').submit(function (ev) { 
     Var myID = this.id; // this refers to the form, and id is a droperty of the element so you can access it directly.. 
     ev.preventDefault(); // esv -> ev as that is the name you use as the parameter 
     $.ajax({ 
      url: "/update", 
      data: $(this).serialize(), 
      dataType: "html", 
      success: function (data) { 
       $('#' + myID).html(data); 
      } 
     }); 
    }); 
}); 
+0

這幾乎做到了。非常感謝這是我的頭腦。我需要編輯最後部分:$(「div#」+ myID).html(data);爲了確保它將數據放入正確的div而不是表單中。 – Geoff1977

+0

@geof,id屬性**必須**在文檔中是唯一的。更好地使用固定的前綴使它們在表單和容器之間唯一。就像形式爲'id =「yourid」'和div'id =「 yourid容器「'。這將使文檔有效,你可以使用$('#'+ myID +'-container')。html(data);' –

相關問題