按键输入后清除文本字段

时间:2015-07-19 19:02:48

标签: javascript jquery forms textfield

我正在使用一个简单的聊天脚本,需要一种方法来在按Enter键后清除文本字段。

我用onfocus鼠标点击它来清除文本字段,但是按键操作让我不知所措。还有一种方法可以使用一个命令来使代码更清洁吗?

<form onsubmit="chat.sendMsg(); return false;">
    <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
    <input type="submit" value="Enter" />
</form>

2 个答案:

答案 0 :(得分:3)

首先,使用事件属性,现在已经过时到了不好的做法。相反,使用JS连接您的事件。在您使用jQuery标记问题时,请尝试以下操作:

<form>
    <input type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
    <input type="submit" value="Enter" />
</form>
$(function() {
    $('form').submit(function(e) {
        e.preventDefault();
        chat.sendMsg();
        $('#msg').val(''); // clear the message box
    });

    $('#msg').on('focus', function() {
        this.value = '';
    });
});

请注意,我删除了blur处理程序,因为它实际上没有做任何事情。

答案 1 :(得分:2)

<form onsubmit="chat.sendMsg(); this.msg.value = ''; return false;">
    <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
    <input type="submit" value="Enter" />
</form> 

<form onsubmit="chat.sendMsg(); this[0].value = ''; return false;">
        <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" />
        <input type="submit" value="Enter" />
</form>
相关问题