jquery can't get the value from an input element (2)

↘锁芯ラ 提交于 2019-12-24 15:11:34

问题


I am using jquery trying to retrieve the value of a text input but it is not working. can anyone see what I am doing wrong? http://jsfiddle.net/silvajeff/4Sb8K/3/

<table id="oustandingItems">
  <tr><th>Category</th></tr>
  <tr><td><input name="mytest" /></td></tr>
  <tr><td><input name="mytest" value="123"/></td></tr>
  <tr><td><input name="mytest" /></td></tr>
  <tr><td><input name="mytest" /></td></tr>
</table>


<button id="findRow">Find Row</button>
<input type="text" id="myRow" />

$("#findRow").click(function() {   
  var tableRow = $('#oustandingItems tr:has(td input[value!=""])').prevAll().length;  
 var myValue = $('#oustandingItems input:has(td input[value!=""])').val();
  $("#myRow").val(myValue);
});

回答1:


You can simplify your selector to #oustandingItems tr input[value!=""]

$("#findRow").click(function() {
  var myValue = $('#oustandingItems tr input[value!=""]').val();
  $("#myRow").val(myValue);
});

JSFiddle




回答2:


You can try this one: http://jsfiddle.net/4Sb8K/6/

$("#findRow").click(function() {   
  var myValue = $('#oustandingItems').find('input[value!=""]').val();
  $("#myRow").val(myValue);
});



回答3:


Your selector to find the inputbox with value is wrong.

- var myValue = $('#oustandingItems input:has(td input[value!=""])').val();

+ var myValue = $('#oustandingItems input[value!=""]').val();

BTW, .val() method only returns the value of the first element, if your selector matches multiple elements. If you need to traverse all elements, use .each() method.



来源:https://stackoverflow.com/questions/14333135/jquery-cant-get-the-value-from-an-input-element-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!