1

My code is working great when the user input first character as a white space but if user insert a string and come back to first position then it take white space. How I prevent user to do this ? "#M1_7_othe" this is the id of input box.

$(function(){    
    var pp;    

    $("#M1_7_other").keydown(function(event) {
        pp =$("#M1_7_other").val();
        if( ($("#M1_7_other").val().length) == 0 ) {
            if( event.keyCode == 32 ) {
                return false;
            }
        }
    });
});
rorofromfrance
  • 1,854
  • 12
  • 21
user3569089
  • 1
  • 1
  • 3

4 Answers4

4

This doesn't prevent it but it delets the whitespace. Use trim() for deleting the whitespace in front and at the end

var str = "       Hello World!        ";
alert(str.trim()); 

And the output will be:

Hello World!

IE9, IE8:

Look at this topic:

.trim() in JavaScript not working in IE

Community
  • 1
  • 1
Aerox
  • 69
  • 3
1

You could use oninput event instead, which will handle string pasted from context menu too:

$(function () {
    $("#M1_7_other").on('input', function (event) {
        var posCaret = this.selectionStart;
        this.value = this.value.replace(/^\s+/, '');
        setCaretPosition(this, posCaret);
    });
});

Here is the setCaretPosition() method, from HERE:

function setCaretPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

--DEMO--

Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

Please try this,

    $(function(){    
    var pp;    

    $("#M1_7_other").keydown(function(event) {
        pp =$("#M1_7_other").val();          
            if( event.keyCode == 32 && document.getElementById("M1_7_other").selectionStart === 0) {

                return false;
            }
    });
});
0

My code is Dynamic which works on all textbox and it works on all browser including Internet Explorer try this.

    $(function(){
    var pp;
    $("input:text").keydown(function(event){

    if(($(this).val().length)==0 && event.keyCode==32)
    {
    return false;
    }
   })
    .keyup(function(event)
   {
    pp = $(this).val();
    if(pp.charAt(0)==' ')
   {
   var pbb = $.trim(pp);
   $(this).val(pbb);
   }
    });
    });