Reputation: 17077
Using jQuery and the HTML below, can someone please suggest what's the best (ie. most efficient) way to retrieve span.street_address_display from $("input"). Thanks.
<tr>
<th class="address_name" scope="row">Work</th>
<td class="address_entry">
<span class="street_address_display">123456 ABC Street</span>
<span class="city_display">Vancouver</span>,
<span class="state_province_display">British Columbia</span>
<span class="country_display">Canada</span>
<span class="post_code_display">V1A2B3</span>
</td>
<td class="address_select"><input value="address_2" name="address_select" type="radio" /></td>
</tr>
Upvotes: 3
Views: 230
Reputation: 343
I'm not quite sure if you looking to get the value of the input, the value of class "street_address_display" but this would work for each respectively:
$('.street_address_display').html();
$('input').val();
Upvotes: 1
Reputation: 30012
You could simply do this as well:
$(".street_address_display",$("input").parents("tr"));
Note that it will only give you one result, so if you got multiple inputs, you need to define which one you are after, unless you can just use this
.
For example:
$(".street_address_display",$("input:first").parents("tr"))
or
$(".street_address_display",$(this).parents("tr"))
Upvotes: 2
Reputation: 3743
This works:
var $my_span = $('input[name="address_select"]').parent().prev().children().first()
Upvotes: 1
Reputation: 21388
If you're calling it within a function that has this
being scoped to the input (otherwise you need to replace this
with something that grabs the input), something like
$(this).parent().prev().children('span.street_address_display')
should take you to the span. As far as efficiency, I'd say the biggest place you'll notice differences will be something like IE, or places that can't grab by Tag or Class.
Mind you, this is doing direct lookups, so one level up with .parent()
rather than going up until you find a td
, the previous td
and then only direct children of that td
that are span
and have the class street_address_display
. This won't scrape deeply, so you're losing flexibility, but less look ups translates to faster. It's up to you if it's worth it.
Upvotes: 3
Reputation: 28220
var $input = $('input');
var street_address_display = $input.closest('td').prev().find('span.street_address_display');
or, if there are no other such spans in the table row,
var street_address_display = $input.closest('tr').find('span.street_address_display');
Upvotes: 3