0

I have some jQuery code where I want to find user's input length but every time instead of giving user's input length, it is returning max length defined on the text box. How can I achieve this?

What I want to achieve using jQuery is this: I want whenever user type 0, I want to convert it to 000, but when user type 70, it is also converting it to 000, which I want to keep as it is. So I want this to fire only when user input length is less then 1. Input user box has a max length defined in HTML which is 3.

Your input is really appreciated.

Here is my jQuery code:

$(document).ready(function(){
    $("input:[id*=txtFairIsaacScore]").keydown(function(event){
        if($("input:[id*=chkFairIsaacScoreEdited]").is(":checked")){
            //$("input:[id*=txtFairIsaacScore]").unmask();

            var cp_value =  $("input:id*=txtFairIsaacScore]").val().length;

            alert(cp_value);

            if(cp_value <= 1){
                if ((event.keyCode == 48) || (event.keyCode == 96)){
                    $("input:[id*=txtFairIsaacScore]").val("000");
                }
             }
        }
    });
});
Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
ana
  • 37
  • 1
  • 1
  • 11

2 Answers2

4
<input type='text' id='inp'/>

$('#inp').live('keyup',function(){
    alert($(this).val().length)
})

this works fine for me u can check here http://jsfiddle.net/nrVGL/1/

Sedat Başar
  • 3,740
  • 3
  • 25
  • 28
  • 1
    .live() has been removed from jQuery as of 1.9, use .on() see http://stackoverflow.com/questions/1481152/jquery-how-to-detect-a-textboxs-content-has-changed – Wes Jan 07 '14 at 23:12
0

Not sure for the length part ...

you can check -

<input type='text' id='test' maxlength='3'/>

$('#test').bind('keyup',function(){
    if($(this).val().length < 1)
        $('#test').val('000');

})

http://jsfiddle.net/nrVGL/7/

Jayendra
  • 52,349
  • 4
  • 80
  • 90
  • have added to fiddle. if you do focus out with no input 000 should be populated. if input by the user it should remain as is. Can you modify the fiddle and let us know whats not working ? – Jayendra Oct 07 '11 at 14:35