jQuery clear input text on focus

2019-04-05 08:04发布

I have this jQuery script:

$(document).ready(function() {
    $(':input:enabled:visible:first').focus();
    $('.letters').keyup( function() {
        var $this = $(this);
        if($this.val().length > 1)
            $this.val($this.val().substr(0, 1));
            $(this).next('input').focus();
        });
});

It will set focus on the first input='text' field on page load. When a user enters a character it will move focus to the next following input field. It will also limit the number of characters allowed in each field (currently 1 character).

I wonder if it's possible to clear the current value of the input field on focus. Both when a user clicks with the cursror to focus the field but also when the $(this).next('input').focus(); sets focus on the next input field.

Also is it possible to validate the characters to only allow alphabetical characters?

3条回答
看我几分像从前
2楼-- · 2019-04-05 08:32

use this

$( document ).ready(function() {
  var search_text_s = "WYSZUKAJ";

  // author ZMORA
  // search input focus text
  $("#searchClear").focus(function() {
    if(this.value == search_text_s){
      this.value = "";
    }
  }).blur(function() {
    if(this.value != search_text_s){
      this.value = search_text_s;
    }
  });
});
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-04-05 08:44

To filter the input, use

​$('input').on('keydown', function(e) {
    if( !/[a-z]|[A-Z]/.test( String.fromCharCode( e.which ) ) )
        return false;
});​​​​​​​​

To clear the input field on click & focus, use

$('input').on('click focusin', function() {
    this.value = '';
});

Be aware of that this event will fire twice, when you click into a non-focused input control in its current form.

Demo: http://jsfiddle.net/xbeR2/

查看更多
再贱就再见
4楼-- · 2019-04-05 08:47

To answer your focus question, yes you can do that:

$("input").focus(function() {
  this.value = "";
});

To answer the only allow letters question, this has been asked before.

查看更多
登录 后发表回答