Reputation: 736
Script #1:
<textarea></textarea>
$('textarea').each(function() {
var $placeholder = "First line\nSecond one";
console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder);
$(this).attr('value', $placeholder);
$(this).focus(function(){
if($(this).val() == $placeholder){
// reset the value only if it equals the initial one
$(this).attr('value', '');
}
});
$(this).blur(function(){
if($(this).val() == ''){
$(this).attr('value', $placeholder);
}
});
// remove the focus, if it is on by default
$(this).blur();
});
returns
<textarea>First line
Second one</textarea>
Script #2:
<textarea data-placeholder="First line\nSecond one"></textarea>
$('textarea').each(function() {
var $placeholder = $(this).attr('data-placeholder');
console.log('[function] shikamo__edit_placholder, data-placeholder: ' + $placeholder);
$(this).attr('value', $placeholder);
$(this).focus(function(){
if($(this).val() == $placeholder){
// reset the value only if it equals the initial one
$(this).attr('value', '');
}
});
$(this).blur(function(){
if($(this).val() == ''){
$(this).attr('value', $placeholder);
}
});
// remove the focus, if it is on by default
$(this).blur();
});
returns
<textarea data-placeholder="First line\nSecond one">First line\nSecond one</textarea>
How can I get the same result with a line break
<textarea data-placeholder="First line\nSecond one">First line
Second one</textarea>
from Script #2?
Upvotes: 2
Views: 103
Reputation: 2617
using @Ishita's answer
$(this).attr('value', ($placeholder.replace(/\\n/g, "\n")));
EDIT
it's because when you read a property from placeholder attribute it's seen not as a line break but as a regular \n
string. if you change that string back into line break, you are at home.
Upvotes: 2
Reputation: 4824
Use
<br/> instead of /n
Or if you are rendering a string,
replace /n with <br/>
// this is code for string replacement
replace(/\n/g, "<br />");
Basically, write this code
$(this).attr('value', ($placeholder.replace(/\n/g, "<br />")));
Upvotes: 1