2013-08-31 57 views
0

hidden_​​field_tag我在其中有一條線一個HAML文件中像如下:設定值在HAML

%td 
    = hidden_field_tag "item1" 

我jQuery中如下設置它的值:

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

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

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

即使它不工作也。其實這樣當我張貼,在處理頁面的時候,我打印參數項標籤與表單關聯,它是印刷爲:項目=>「」

編輯:它的HTML源代碼如下:

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

沒有值字段即將到來。

+0

是什麼您當前的HAML將展示您的示例(瀏覽器中查看的HTML源代碼是什麼)? – RobM

+0

一般來說,你有什麼看起來不錯。我爲你創建了一個示例來顯示閱讀和設置jQuery在這裏的值:*** http://jsfiddle.net/T2v8K/2***。嘗試設置一個像這樣的默認值並查看您是否正確讀出了表單文章中的值。 – RobM

回答

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); 
+0

你好?你試過這個嗎? – RobM