2016-11-15 49 views
2

我想獲取文本框內的值。 textField在表中的<td>內。當我點擊按鈕時,我想要文本框內的文本,使用它的效果非常好。獲取表格中的type = text的值

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>jQuery Bind Click Event to Dynamically added Elements</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 

      $('#main').on("click", 'input[type="button"]', function() { 
       var customerId = $(this).parent().siblings('td:eq(2)').text(); 
       $('#texti').text(customerId); 
      }); 

    }); 


</script> 
</head> 
<body> 
    <button>Add new list item</button> 
    <p>Click the above button to dynamically add new list items. You can remove it later.</p> 
    <table id="main"> 
    <tr> 
     <td>list item 1 </td> 
     <td><input type='text' name='textN' id='textN' value='asdf'/></td> 
     <td>list item 3 </td> 
     <td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td> 
    </tr> 
    <tr> 
     <td>list item 4</td> 
     <td><input type='text' name='textN' id='textN' value='asdf2'/></td> 
     <td>list item 6</td> 
     <td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td> 
    </tr> 
    <tr> 
     <td>list item 7</td> 
     <td><input type='text' name='textN' id='textN' value='asdf3'/></td> 
     <td>list item 9</td> 
     <td ><input type='button' value='Update' name ='updateBox' id='updateBox' /></td> 
    </tr> 
    </table> 
    <a name="texti" id="texti"> x </a> 
</body> 
</html> 

它給了我一個空白變量。怎麼修?

+1

的ID應該是唯一的。 –

回答

2

只有你需要的是從當前行輸入find並使用.val()得到它的值。

這裏是解決方案:jsfiddle

$('#main').on("click", 'input[type="button"]', function() { 
      var customerId = $(this).parent().siblings('td:eq(1)').find('input').val(); 
      $('#texti').text(customerId); 
}); 
+0

你是偉大的先生! –

+0

不客氣! –

0

使用.val()而不是.text().val()用於輸入值,而.text()嘗試在標籤之間獲取文本。