How to force input to only allow Alpha Letters?

后端 未结 9 1502
长发绾君心
长发绾君心 2020-12-01 06:52

using jQuery here, however unable to prevent numbers from being typed into the input field

http://codepen.io/leongaban/pen/owbjg

Input



        
9条回答
  •  失恋的感觉
    2020-12-01 07:23

    A lot of the other solutions that use keypress will not work on mobile, you need to use input.

    html

    
    

    jQuery

    $('#name').on('input', function() {
        var cursor_pos = $(this).getCursorPosition()
        if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
            $(this).val($(this).attr('data-value'))
            $(this).setCursorPosition(cursor_pos - 1)
            return
        }
        $(this).attr('data-value', $(this).val())
    })
    
    $.fn.getCursorPosition = function() {
        if(this.length == 0) return -1
        return $(this).getSelectionStart()
    }
    $.fn.setCursorPosition = function(position) {
        if(this.lengh == 0) return this
        return $(this).setSelection(position, position)
    }
    $.fn.getSelectionStart = function(){
      if(this.lengh == 0) return -1
      input = this[0]
      var pos = input.value.length
      if (input.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', input.value.length)
        if (r.text == '') 
        pos = input.value.length
        pos = input.value.lastIndexOf(r.text)
      } else if(typeof(input.selectionStart)!="undefined")
      pos = input.selectionStart
      return pos
    }
    $.fn.setSelection = function(selectionStart, selectionEnd) {
      if(this.lengh == 0) return this
      input = this[0]
      if(input.createTextRange) {
        var range = input.createTextRange()
        range.collapse(true)
        range.moveEnd('character', selectionEnd)
        range.moveStart('character', selectionStart)
        range.select()
      }
      else if (input.setSelectionRange) {
        input.focus()
        input.setSelectionRange(selectionStart, selectionEnd)
      }
      return this
    }
    

提交回复
热议问题