Chris Edwards Chris Edwards - 1 year ago 63
jQuery Question

jquery highlight cell on text input

I am trying to figure out how to have a table cell highlight when a value greater than zero is input into a text input. I have seen plenty of examples on checkboxes but can't seem to find an example on a text input.

Any help is greatly appreciated.

Answer Source

Show us some markup or the input field. Below answer is under the assumption that input is directly inside td.

DEMO

HTML:

<table>
    <tr>
        <td>
            <input type="text" class="number" />
        </td>
        <td>
            <input type="text" class="number" />
        </td>
    <tr>        
        <td>
            <input type="text" class="number" />
        </td>
        <td>
            <input type="text" class="number" />
        </td>
    </tr>
</table>

JS:

$('.number').keyup(function() {
    var number = $(this).val();

    try {
        number = parseInt(number, 10);
        if (number > 0) {
            $(this).closest('td').addClass('highlight');
        } else {
            $(this).closest('td').removeClass('highlight');
        }

    } catch (e) {}
});

CSS:

td { border: 1px solid black; padding: 10px; }

td.highlight { border: 1px solid red; }

input { width: 100px; }