jQuery jQuery清除焦点上的输入文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13978621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:09:30  来源:igfitidea点击:

jQuery clear input text on focus

jqueryinputfocusclear

提问by David

I have this jQueryscript:

我有这个jQuery脚本:

$(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).

它将input='text'在页面加载时将焦点设置在第一个字段上。当用户输入一个字符时,它会将焦点移动到下一个输入字段。它还将限制每个字段中允许的字符数(当前为 1 个字符)。

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.

我想知道是否可以清除焦点上输入字段的当前值。当用户使用光标单击以聚焦该字段时,以及当$(this).next('input').focus();集合聚焦于下一个输入字段时。

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

是否可以验证字符以只允许字母字符?

回答by jAndy

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

要清除click&上的输入字段focus,请使用

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

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

请注意,当您单击当前形式的非焦点输入控件时,此事件将触发两次。

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

演示http: //jsfiddle.net/xbeR2/

回答by Jason Towne

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

要回答您的焦点问题,是的,您可以这样做:

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

To answer the only allow letters question, this has beenaskedbefore.

为了回答唯一的允许字母问题,之前已经这个问题。

回答by ZMORA

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;
    }
  });
});