我有一个HAML文件,其中有一行如下:
%td
= hidden_field_tag "item1"
我在jquery中设置它的值如下:
$("#item1").val(1)
但它不起作用,所以我做了如下:
$("#item1").attr("value",1)
即使它也不起作用。实际上,item标签与表单相关联,所以当我发布它时,在我打印参数的处理程序页面中,它打印为:item =>“”
编辑:其HTML源代码如下:
<input id="item1" name="item1" type="hidden">
没有值字段。
答案 0 :(得分:1)
一般来说,你看起来很好。我为您创建了一个示例,用于在jQuery中显示阅读和设置值: http://jsfiddle.net/T2v8K/2 。这应该可以帮助您进行调试。
HTML:
<div>
<form id="myForm">
<table>
<tr>
<td>normal input: <input id="newValue" name="newValue" value="1" /></td>
<td>hidden input: <input id="item1" name="item1" type="hidden" value="someDefaultValue"/></td>
</tr>
</table>
</form>
<button id="showVal" type="button">Show Hidden Input Value</button>
<button id="setVal" type="button">Set Hidden Input Value</button>
</div>
JavaScript / jQuery:
$( document ).ready(function() {
var beforeValue = $( "#item1" ).val();
//alert( "Before = " + beforeValue );
var afterValue = $( "#item1" ).val();
//alert( "After = " + afterValue );
$( "#showVal" ).click( function() {
ShowHiddenInputValue();
})
$( "#setVal" ).click( function() {
SetHiddenInputValue();
})
});
function ShowHiddenInputValue() {
//Show the current value of the hidden input
var hiddenInputValue = $( "#item1" ).val();
alert( "Hidden Input Value = " + hiddenInputValue );
}
function SetHiddenInputValue(){
//Get the value from the input
var newHiddenInputValue = $( "#newValue" ).val();
//Set the hidden input
$( "#item1" ).val(newHiddenInputValue);
ShowHiddenInputValue();
}
尝试设置这样的默认值,看看你是否正确读出了表单中的值。
此外,如果您不确定jQuery是否正常工作(可能未正确引用),您可以通过在JavaScript中检查此类警告中的版本号来测试:
alert($().jquery);