Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a placeholder attribute if "value" field is empty

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">
like image 834
take2 Avatar asked Oct 20 '12 22:10

take2


1 Answers

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.

like image 195
David Thomas Avatar answered Nov 03 '22 00:11

David Thomas