Reputation: 12512
I need to come up with a way to check for a specific value withing a hidden element and if found, display a particular message. I think it can be done with a jQuery, but I am struggling with a way to do it...
Here's a simplified version of my code. I need to put a message in a TD with class
outputHere
The message is conditional, based on whether I will find class sku
that is withing a span, that's inside a nested table, in a TR
that is hidden...
If SKU value is found I output it, if not I look for ITEMID, and if neither is found, I put a default message...
<table>
<tr>
<td>
<div class="outputHere">val</div>
</td>
</tr>
<tr>
<td>
<div>
<table class="nested">
<tr>
<td>
<span class="sku">SKU number</span>
</td>
</tr>
</table>
<tr>
<td>
</div>
</td>
</tr>
</table>
A bit overwhelmed... Thinking it should be something like:
$('.outputHere').each(function() {
var $message =
$(this).parents('table').closest('tr').find('span.sku');
if ($message) {
$(this).text($message); } else {
$(this).text('Default message');
}
});
UPDATE
What if my SKU cell did not have a class="sku" but rather SKU number, how would I locate the SKU value then?
<table>
<tr>
<td>
<div class="outputHere">val</div>
</td>
</tr>
<tr>
<td>
<div>
<table class="nested">
<tr>
<td>
<span class="label">SKU:</span>
</td>
<td>sku_value</td>
</tr>
</table>
<tr>
<td>
</div>
</td>
</tr>
</table>
Upvotes: 0
Views: 49
Reputation: 55740
$('.outputHere').each(function() {
var $this = $(this);
var $span = $this.closest('tr').next('tr').find('span.sku');
if($span.html().length) {
$this.text($span.html());
} else {
$this.text('Span Not found !!');
}
});
UPDATED FIDDLE
If that was the case I would use the :contains selector
$('.outputHere').each(function() {
var $this = $(this);
var $span = $this.closest('tr').next('tr').find('.label:contains(SKU)');
if($span.html().length) {
var num = $span.html().split(':')[1];
$this.addClass('changed').text(num);
} else {
$this.text('SKU Not found !!');
}
});
Upvotes: 1
Reputation: 195972
If the html structure (although it seems a bit excessive) is like the question then use
$('.outputHere').each(function() {
var $message = $(this).closest('table').find('span.sku');
if ($message.length) {
$(this).text($message.text());
} else {
$(this).text('Default message');
}
});
Demo at http://jsfiddle.net/gaby/kjcXH/
Upvotes: 0