2014-03-24 30 views
1

我將數據庫中的行顯示爲一個表,每行都是一個動態構建的獨立窗體。表單可以通過該行的主鍵id來標識。我希望能夠發送相應的表單到javascript和訪問值,但不知道如何。如何將動態構建的表單發送給JavaScript?

這是使用.erb

<% thresholds.each do |threshold| %> 
<form name = "threshold<%= threshold["id"]%>"> 
    <td> 
     <input type="text" name="score" value="<%= threshold["score"] %>" size="1"> 
    </td> 
    <td> 
     <button onClick="saveThreshold(this.form)">Save</button> 
    </td> 
    <td> 
     <button id="deleteThreshold">Delete</button> 
    </td> 
</form> 
<% end %>  

的Javascript:

function saveThreshold(form) { 
    alert('my score is: ' + form.score.value); 
} 

但它說的形式是不確定的。

+0

你需要引用的形式(可能的document.getElementById?)。你的參數不會被注入。 –

+0

一個按鈕有一個默認的'submit'類型,所以如果你不想在點擊按鈕時提交表單,改變它的類型 - >' ' – adeneo

+0

獲取單擊事件的目標並瀏覽目標元素的父節點以查找具有tagName'form'的元素。 – dherbolt

回答

1

選擇器this.form不是從DOM訪問表單元素的正確方法。嘗試:

<% thresholds.each do |threshold| %> 
<form name="threshold<%= threshold["id"]%>"> 
    <td> 
     <input type="text" name="score" value="<%= threshold["score"] %>" size="1"> 
    </td> 
    <td> 
     <button onClick="saveThreshold(threshold<%= threshold["id"]%)">Save</button> 
    </td> 
    <td> 
     <button id="deleteThreshold">Delete</button> 
    </td> 
</form> 
<% end %> 

這樣,你通過表單name屬性所獲得的價值,而不是this.form

相關問題