views:

93

answers:

2

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.

+3  A: 

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()
Nick Craver
Beat me to it. Nice and simple.
macca1
Raja
A: 

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>
Glennular