how to get the value from a textbox that is next to my text

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-25 00:05:21

问题


i have an html page where i have a table of items (one item per row) where each item is a html link that says "Add" and there is a textbox next to each link with a number in it.

the text link and the textbox are in the same td inside the row of the table.

how do i, using jquery, capture the value from the textbox that is to the right of the link i click on.


回答1:


You could give your link a class, then do this:

$("a.myClass").click(function() {
  alert($(this).next().val());
});

If you have a lot of links, or they're dynamically added, change it a bit to use .live(), like this:

$("a.myClass").live('click', function() {
  alert($(this).next().val());
});

If you wanted to move the textbox around, have an element in-between, etc but it's still the only input in the cell, you could change this: $(this).next().val() to something like this:

$(this).closest('td').find(':text').val()



回答2:


I would suggest using class names to remove design form the functions. Based on Nick Craver's example you are relying on the design to not change. I.e. a design change would require functionality change. The below example would work in more of scenarios, regardless of the HTML.

<script type="text/javascript">
$(function() {  
    $(".row .rowClicker").click(function(){
        alert($(this).parents(".row").find(".rowVal").val());
    });
});
</script>

<div class="row" ><input class="rowVal" /> <a class="rowClicker">click</a></div>
<div class="row" ><input class="rowVal" /> <div id="newparent"><a class="rowClicker">click</a></div></div>
<div class="row" ><input class="rowVal" /> <a class="rowClicker">click</a></div>


来源:https://stackoverflow.com/questions/2668464/how-to-get-the-value-from-a-textbox-that-is-next-to-my-text

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