2017-07-18 73 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