2014-04-04 124 views
0

我正在嘗試創建一個提交表單,該表單在點擊div後顯示,然後檢索填充的表單數據。以下是我現在玩了一天的測試。變量「term」始終打印爲undefined。有人能幫助我嗎?jquery獲取表單數據

$(document).ready(function() { 
    $("#nexttable").on("click", "#addcomment", function() { 
     document.getElementById("nexttable").innerHTML = "<form action='maindatabase.php' id='commentform' method='post'><textarea name='newcomment' placeholder='Start typing your comment... (required)' rows='5' cols='50' required></textarea><br />" 
     + "<span id='sbutton'><input type='button' value='Submit'></span><input type='hidden'  name='inputtype' value='3'></form>"; 
    }); 
}); 

$(document).ready(function() { 
    $("#nexttable").on("click", "#sbutton", function() { 
     var $form = $(this); 
     var term = $form.find("input[name='newcomment']").val(); 
     document.getElementById("nexttable").innerHTML = term; 
    }); 
}); 

回答

2

名爲newcomment,頁面上沒有輸入的文本區域即

$form.find("input[name='newcomment']").val(); 

不會找到任何東西,它應該是

$form.find("textarea[name='newcomment']").val(); 

還有一個問題與this,因爲它是一個委託事件處理程序

$(document).ready(function() { 
     $("#nexttable").on("click", "#sbutton", function() { 
      var $form = $(this); // <-- HERE, the this I do believe is in reference to the #sbutton element, not anyting to do with a form 
      var term = $form.find("input[name='newcomment']").val(); 
      document.getElementById("nexttable").innerHTML = term; 
     }); 
    }); 

我會改變它的東西更像

$(document).ready(function() { 
     $("#nexttable").on("click", "#sbutton", function() { 
      var $form = $(this).parents('form'); // <-- HERE, actually get the form element, which will be a prent of this element clicked ont 
      var term = $form.find("input[name='newcomment']").val(); 
      document.getElementById("nexttable").innerHTML = term; 
     }); 
    }); 
+0

感謝您的回答。我當然確實錯過了這個問題,但即使在糾正之後,打印輸出也表明變量「term」未定義。還有什麼你認爲可能是錯誤的代碼? – Sandor

+0

啊。我認爲這可能是你的處理程序中的這種情況,我會添加更多的代碼到我的回答 – OJay

+0

在此先感謝! – Sandor