简体   繁体   中英

How to fire an event only when text is entered in an input box but not removed?

The following code snippet triggers an alert event when a number is entered (or removed from) into a 9 * 9 Sudoku grid.

   $('table tr td input').on({"input": function () {
            var cell = $(this).val();

            if (!$.isNumeric(cell)) {
                alert("Please enter only numbers from 1 to 9");
            }

   }});

But how to remove the alert message when text is removed ? It has to be triggered only when number is entered.

Change

if (!$.isNumeric(cell)) {

to

if (cell && !$.isNumeric(cell)) {

I'd do the following.

$('table tr td input').on({"input": function () {
        var cell = $(this).val();

        if (cell.length > 0 && !$.isNumeric(cell)) {
            alert("Please enter only numbers from 1 to 9");
        }
}});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM