Reputation: 306
I am trying to hide the tr having any td's value is Value1.
Below code is working fine. But, When I use variable instead of value, the code does not work.
I want it to work using variable.
<input type='button' value='hide/show' />
<table id="mytable">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>Value3</td>
</tr>
<tr>
<td>Value4</td>
<td>Value5</td>
<td>Value6</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
var this_value = "Value1";
$('input').click(function()
{
// Working Fine with Value
$('td:contains("Value1")').parent().toggle();
// Not Working with Variable
// $('td:contains(this_value)').parent().toggle();
});
</script>
Upvotes: 3
Views: 217
Reputation: 104
The problem with your code is that 'td:contains(this_value)'
is one string and the parser does not know that this_value
is a variable. It is just registered as a part of the string.
As others have mentioned, you need to separate the variable from the string via concatenation or by using a template literal.
ES5 concatenation:
'td:contains('+this_value+')'
ES6 template literal
`td:contains(${this_value})`
Upvotes: 0
Reputation: 30739
You need to concatenate that value like $('td:contains("'+this_value+'")')
:
var this_value = "Value1";
$('input').click(function() {
// Working Fine with Value
$('td:contains("'+this_value+'")').parent().toggle();
// Not Working with Variable
// $('td:contains(this_value)').parent().toggle();
});
<input type='button' value='hide/show' />
<table id="mytable">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>Value3</td>
</tr>
<tr>
<td>Value4</td>
<td>Value5</td>
<td>Value6</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
Upvotes: 1
Reputation: 411
try this
var this_value = "Value1";
$('input').click(function()
{
$('td:contains('+this_value+')').parent().toggle();
});
Upvotes: 2