如何在输入字段中保留一些默认文本? [英] How to keep some default text in the input field?

查看:121
本文介绍了如何在输入字段中保留一些默认文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我是否以正确的方式提问,请原谅。所以在这里。我有一个文本输入字段。我已经有一些占位符文本。但是,当用户点击该字段时,我希望占位符文本消失,并在其中出现一些默认文本,用户无法删除。
因此,当用户提交表单时,收到的数据应该采用这种格式 - 我保留的默认文本+用户提供的文本。如何做到这一点。



以下是我拥有的输入字段的示例。

 < input type =textplaceholder =defaultTextclass =input> 


解决方案

http://jsfiddle.net/429jspyn/2/

  var dft ='DEFAULT  - '; 
$('input.input')。keyup(function(evt){
/ * Key up event要捕获所有的键,keypressed不会捕获iE
backspace * /
/ *如果输入值为空,请不要改变它,保持输入干净* /
if($(this ).val()!=''){
/ *将输入值附加到变量中以便将来改变* /
var txt = $(this).val();
/ * txt.replace删除已添加的默认文本以防止无限预计* /
$(this).val(dft + txt.replace(dft,''));
}
} ).keydown(function(evt){
/ *)按键是在用户删除部分默认文本并删除整个文件之前捕获用户,这样可以保证它在将来保持清洁。* / $ b $ ($(this).val()== dft){
/ *当用户试图删除默认文本时,将输入设置为空白* /
$(this).val('');
/ *阻止进一步解析* /
返回false;
}
});
});

编辑://更新代码,应该很好:)
EDIT2:// added评论

I don't know if I'm asking it the right way, so please excuse me. So here it goes. I have a text input field. I already have some placeholder text in it. But, when the user clicks on that field, I want the placeholder text to disappear and some default text to appear there, which the user cannot delete. So, when the user submits the form, the data recieved should be in this format - "default text that I had kept" + "text the user provided". How do I do that.

Here is an exmaple of the input field I have.

<input type="text" placeholder="defaultText" class="input">

解决方案

http://jsfiddle.net/429jspyn/2/

$(function(){
    var dft = 'DEFAULT - ';
    $('input.input').keyup(function(evt){
        /* Key up event to catch all keys, keypressed doesn't catch i.E. 
        backspace*/
        /* If input value is empty don't alter it, that keeps input clean */
        if($(this).val() != ''){
            /* attach value of input to variable to alter it in future */
            var txt = $(this).val();
            /* txt.replace removes already added default text to prevent infinite prepending */
            $(this).val(dft + txt.replace(dft, ''));
        }
    }).keydown(function(evt){
        /* Key down is to catch user before he deletes part of default text and remove whole for him. That keeps it clean in future. */
        if($(this).val() == dft){
            /* Set input empty when user's trying to delete default text */
            $(this).val('');
            /* blocks further parsing */
            return false;
        }
    });
});

EDIT:// Updated code, should be good :) EDIT2:// added comments

这篇关于如何在输入字段中保留一些默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆