2017-07-18 74 views
0

訪問文本框值我正在構建一個動態表,用戶可以添加,刪除或編輯。我有以下幾種:jQuery:無法使用.val()

$(document).on('click', '.edit_rule', function() { 
    // editable text boxes for name and description 
    $(this).closest("tr").find("td:nth-child(2), td:nth-child(3)").each(function() { 
     var html = $(this).html(); 
     var input = $('<input type="text" />'); 
     input.val(html); 
     $(this).html(input); 
    }); 

    // replace Edit and Delete with Save and Cancel 
    $(".edit_rule").replaceWith("<input id='Button' type='button' value='Save' class='sav$ 
    $(".delete_rule").replaceWith("<input id='Button' type='button' value='Cancel' class=$ 

}); 

這一切都工作正常。但是,當我嘗試訪問下一個框中的新值時,該值顯示爲空白。我試圖用.VAL(),現在正在嘗試的.text()如下:

$(document).on('click', '.save_edit', function() { 
    var $row = $(this).closest("tr"); 
    var $name = $row.find("td:nth-child(2)").find('input'); 
    console.log($name.text()); // prints empty string 
}); 

我是相當新的JavaScript,因此有一些奇怪的事情的範圍,我不理解,可防止在單獨的函數中訪問值?還有另一種方法可以做到嗎?

編輯:這裏是相應的HTML

<div id="customperms_table_container" style="height:655px;"> 
    <table id="customperms_table_form" cellpadding="10" cellspacing="$ 
     <caption></caption> 
      <thead> 
       <tr> 
        <th>#</th> 
        <th>Role Name</th> 
        <th>Description</th> 
       </tr> 
      </thead> 
      <tbody> 
      </tbody> 
    </table> 
</div> 
+0

可以從你'$ name.text()'添加HTML標記以及 – guradio

+1

改變'$ name.val()',因爲這已經是一個輸入字段 –

+0

損壞的HTML,右一個更新。 –

回答

0
  1. 問題是td沒有價值。
  2. 解決方案是使用.text().html()得到它的文本或HTML基於評論

你的選擇應該是:

var $name = $row.find("td:nth-child(2)").find('input')// add class or id if there other inputs 
+0

.text()出現空白,並且.html()返回爲'' – Mike

+0

@Mike檢查更新的答案 – guradio

+0

認爲這就是它,但html和text返回空白字符串。它幾乎就好像輸入到文本框中的值在頁面加載後對JavaScript不存在 – Mike

0

對不起損壞的HTML,但guradio的組合Haze修復了它。

var $name = $row.find("td:nth-child(3)"); 
console.log($name.val()); // <-- prints correct value