Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  94] [ 7]  / answers: 1 / hits: 34988  / 12 Years ago, sat, october 20, 2012, 12:00:00

Is there a way to add a placeholder attribute (placeholder tag, not defaultvalue and similar approaches) if you have an text input field that has value property empty?



I have seen many similar questions here, but most of them use defaultvalue. I need placeholder tags and additionally I can't influence HTML output at all.



This is the given HTML output example:



<input type=text value= name=textbox id=edit-textbox>

More From » jquery

 Answers
12

I'd suggest any one of the following approaches:



$('input:text').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = 'placeholdertext';
/* or:
el.placeholder = $('label[for=' + el.id + ']').text();
*/
}
});


JS Fiddle demo using el.placeholder = 'placeholdertext'.



JS Fiddle demo using el.placeholder = $('label[for=' + el.id + ']').text().



Or you could use an array to store the various placeholders:



var placeholders = ['Email address', 'favourite color'];

$('input:text').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = placeholders[i];
}
});​


JS Fiddle demo.



To specify a particular placeholder for a particular element:



var placeholders = {
'one' : 'Email address',
'two' : 'Favourite color'
};

$('input:text').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = placeholders[el.id];
}
});​


JS Fiddle demo.



Added a catch/fall-back in the event that an entry doesn't exist in the placeholders object for a particular input:



var placeholders = {
'oe' : 'Email address', // <-- deliberate typo over there
'two' : 'Favourite color'
};

$('input:text').each(
function(i,el) {
if (!el.value || el.value == '') {
el.placeholder = placeholders[el.id] || '';
}
});​


JS Fiddle demo.


[#82457] Thursday, October 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynnleslis

Total Points: 425
Total Questions: 100
Total Answers: 115

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;