Reputation: 781
I'm using a simple chat script and need a way to clear the text field after pressing enter.
I got it to clear text field on mouse click with onfocus
but keypress eludes me. Also is there a way to do both with one command to make the code cleaner?
<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>
Upvotes: 0
Views: 6262
Reputation: 1279
<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>
or
<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>
Upvotes: 2
Reputation: 337560
Firstly, using the event attributes is, these days, outdated to the point of bad practice. Instead, hook up your events using JS. As you've tagged the question with jQuery, try this:
<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 = '';
});
});
Note that I removed the blur
handler as it didn't actually do anything.
Upvotes: 3