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">
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With