JavaBeginner
JavaBeginner

Reputation: 115

keypress event not working in jQuery

I have a text box in my web-page. I want to prevent user from entering space without entering any character. I have this now.

    $('#DivisionName').bind('keypress', function(e) {
        if($('#DivisionName').text().length == 0){
            if (e.which == 32){//space bar
                e.preventDefault();
            }
        }
        else{
            alert("if not working");
        }
    });    

This is my HTML

    <input maxLength=15 name="DivisionName" id="DivisionName" size=15> 

When I run the code, it is allowing user to enter space without giving any character. Where am I going wrong?

Upvotes: 1

Views: 1825

Answers (5)

Jaimin
Jaimin

Reputation: 8020

Try this,

 <input type="text" maxLength=15 name="DivisionName" id="DivisionName" size=15> 

$("#DivisionName").keypress(function(event) {
if($('#DivisionName').val().length == 0){
            if (e.which == 32){//space bar
                e.preventDefault();
            }
        }
        else{
            alert("if not working");
        }

});

Upvotes: 0

Sasidharan
Sasidharan

Reputation: 3750

Working Sample

HTML

<input type="text" id="DivisionName" />

Javascript

window.onload = function () {
    var inputEl = document.getElementById("DivisionName");
    inputEl.addEventListener("keydown", function (e) {
        if (inputEl.value.length == 0) {
            if (e.keyCode == 32) {
                e.preventDefault();
            }
        }
    });
}

Upvotes: 0

knagode
knagode

Reputation: 6125

You have to enslose your code into

$(function() {
// CODE
}

It works - check here: http://jsfiddle.net/Dufvg/

And yes ... Replace .text() with .val()

Upvotes: 0

Rejayi CS
Rejayi CS

Reputation: 1061

try it like this :

$("#DivisionName").keypress(function() {
console.log("keypress called.");
});

Upvotes: 0

Amit
Amit

Reputation: 15387

text() is use when div, span value. In case text box always use val()

Try this

$('#DivisionName').bind('keypress', function(e) {
    if($('#DivisionName').val().length == 0){
        if (e.which == 32){//space bar
            e.preventDefault();
        }
    }
    else{
        alert("if not working");
    }
}); 

You are not defining input type, so add type="text"

  <input type="text" maxLength=15 name="DivisionName" id="DivisionName" size=15> 

Upvotes: 2

Related Questions