Reputation:
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">
Upvotes: 0
Views: 525
Reputation: 767
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
Upvotes: 3
Reputation: 1
add id attribute to your input
<input type="text" placeholder="defaultText" class="input" id="myInput">
and on click event do this
$("myInput").click( function() {
this.html("defaultText");
this.attr("disabled","disabled");
}
Upvotes: 0