0

我有一个 HAML 文件,其中有如下一行:

 %td
   = hidden_field_tag "item1"

我在 jquery 中设置它的值如下:

 $("#item1").val(1)

但它不工作,所以我做了如下:

 $("#item1").attr("value",1)

即使它也不起作用。实际上,项目标签与表单相关联,所以当我发布它时,当我打印参数时,在处理程序页面中,它打印为 :item =>""

编辑:它的 HTML 源代码如下:

<input id="item1" name="item1" type="hidden">

没有值字段出现。

4

1 回答 1

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);
于 2013-09-01T07:34:29.423 回答