killereks killereks - 4 months ago 9
jQuery Question

JQuery hiding elements bigger than variable in table

<input type="checkbox" id="canafford"></input>


I want it so when you check that checkbox, only upgrades that you can buy will appear. This is my upgrades code (its a lot longer but i will show you only 1 part).

<tr id="up1">
<td><button onclick="upgrade(2, 1)">Upgrade</button></td>
<td>2 gold</td>
<td>x2 Resting speed.</td>
</tr>


Each of them have id up1 up2 up3 etc. All i need is if gold (currency) is lower than its price it will hide.
Price is the second td in all of them. in this case its 2 gold

Answer

You can do this on few possible ways. This is one of working solutions.

Please check this snippet and feel free to edit variable 'goldAvailable'. Im actually looping through all tr elements on each click on this checkbox. If it is checked then im taking value from 2nd td item and parsing it to integer so i can compare it to available money. Everything that is higher then available will be hidden. On uncheck of box everything is getting to display:block

var goldAvailable = 3;

$('#canafford').on('click', function(){ 
    if($('#canafford:checkbox:checked').length > 0) {
        $('tr td:nth-child(2)').each(function () {
            var gold = $(this).html();
            gold= parseInt(gold.substring(0,gold.length-4));
            if(gold>goldAvailable) {
                $(this).closest('tr').css('display','none');
            }
        });
    } else {
            $('tr td:nth-child(2)').each(function () {
                $(this).closest('tr').css('display','block');
            });
    }
    
});
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
    <input type="checkbox" id="canafford"> </input>
    <table>
    <tr id="up1">
        <td><button onclick="upgrade(2, 1)">Upgrade</button></td>
        <td>2 gold</td>
        <td>x2 Resting speed.</td>
    </tr>
    <tr id="up1">
        <td><button onclick="upgrade(2, 1)">Upgrade</button></td>
        <td>3 gold</td>
        <td>x2 Resting speed.</td>
    </tr>
    <tr id="up1">
        <td><button onclick="upgrade(2, 1)">Upgrade</button></td>
        <td>4 gold</td>
        <td>x2 Resting speed.</td>
    </tr>
    <tr id="up1">
        <td><button onclick="upgrade(2, 1)">Upgrade</button></td>
        <td>5 gold</td>
        <td>x2 Resting speed.</td>
    </tr>
    </table>
</body>

</html>