March 2, 2012

preventDefault() is not working giving object does not support this property

Question by JainNavneet

I want to set maximum length of a textbox to 7 and stop further keys entering and using preventDefault but its giving error
My Code is below

function crInputRK(ctrlid, ControlValue, size, clsName)                                    {

    var newTextBox = crE('input');
    newTextBox.type = 'text';
    newTextBox.style.fontSize = ".9em";
    newTextBox.style['width'] = size;
    newTextBox.style['height'] = '12px';
    newTextBox.style['float'] = 'none';
    newTextBox.style['margin'] = '0 0 0 10px';//added on 13feb2012
    //newTextBox.maxLength = '3';
    newTextBox.id = ctrlid;

    newTextBox.className = 'inputDate';

    //newTextBox.onchange = "javascript:return EnableButton();";

    //ControlValue = getControlValue(ctrlid);
    if (ControlValue != "")
        newTextBox.value = ControlValue;
    if (ControlValue == "Multiple")
        newTextBox.disabled = true;
      newTextBox.setAttribute("onkeypress", "javascript:SetMaxLength(event,this);");


    return newTextBox;
}


function SetMaxLength(e, txtbox)                                                           {

    var MaxLength = 7;
    if (_$(txtbox.id).value.length >= MaxLength) {
        e.preventDefault();

    }
}

Answer by Starx

It is possible using .preventDefault();

 $("body").find("input[type=text]").each(function(k,v) {
     $(this).on('keypress', function(event) {
        limit = 7; //for example
        val = $(this).val();
        len = val.length;
        if(len > limit-1) { event.preventDefault(); }
             });
    });

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!