2014-03-24 91 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

相关问题