Reputation:
I am trying to create code to swap images in a table based on values from a database. After some research on this site, I have this code, amended for my needs. Not dynamic at this point as the input data at this point is hard coded. The jQuery is not working because I have missed the point on something. Very new to jQuery so would appreciate any help to point me in the right direction.
<table>
<tr>
<td>6</td>
<td id="td1">
<img />
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#td1 img').attr('src' function(){
return parseInt($(this).parent().prev().html()) > 5 ? 'src1','/images/clubsTiny.png' : 'src2','/images/blkCross.png';
});
</script>
Upvotes: 0
Views: 52
Reputation: 9893
First separate $('#td1 img').attr('src', function ()
by ,
. Note that
attr
needs two parameter and each parameter seprates with ,
.
And then changed condition with:
return parseInt($(this).parent().prev().html()) > 5 ? 'images/clubsTiny.png' : 'images/blkCross.png';
Note that ternary conditions is expression ? 'do true one' : 'do false one'
$('#td1 img').attr('src', function () {
return parseInt($(this).parent().prev().html()) > 5 ? 'src1/images/clubsTiny.png' : 'src2/images/blkCross.png';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>6</td>
<td id="td1">
<img />
</td>
</tr>
</table>
Update
For replace content by img
you can use $('#td1').html(img)
function replace() {
let td = $('#td1');
let img = $("<img />");
img.attr("src", ()=> +td.html() > 5 ? 'images/clubsTiny.png' : 'images/blkCross.png')
$('#td1').html(img)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td id="td1">
6
</td>
</tr>
</table>
<button onclick="replace()">click to replace</button>
Upvotes: 1