user1176783
user1176783

Reputation: 673

jquery - How do I add an alert message to this jquery code base?

The Question

To help avoid end-user confusion, I want to add an alert message that pops up if/when the user clicks any other key ["alert('Only Numerical data allowed')"]. So if they press the 'k' the above message will pop up. Can anyone see how to set this code within this code base


The Code

jquery:

$('input.numberinput').bind('keypress', function (e) {
    var w = e.which;
    return (w != 8 && w != 0 && (w < 48 || w > 57) && w != 46) ? false : true;
});

html

<div class="containercontent">

         <div class="label">Enter a number:</div>
        <input type="text" name="txtNumber1" id="txtNumber1" value=""  class="numberinput" />

         <div class="label">Enter a number:</div>
        <input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
    </div>

Upvotes: 1

Views: 43647

Answers (2)

Suave Nti
Suave Nti

Reputation: 3757

Simple :

$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {

    if((e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) )
    {
       alert('Only Numbers');
        return false;
    }
    else{
      return true;
    }
});
});

Link : http://jsfiddle.net/justmelat/EN8pT/

Upvotes: 4

Daniel Li
Daniel Li

Reputation: 15389

Hello again :) I can help you out with this as well:

$(document).ready(function () {
    $('input.numberinput').bind('keypress', function (e) {
        var allow = (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true;
        if (!allow) {
            alert('Only Numerical data allowed');
        }
        return allow;
    });
});?

JSFiddle: http://jsfiddle.net/EN8pT/3/

Enjoy and good luck!

Upvotes: 1

Related Questions