take2
take2

Reputation: 614

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">

Upvotes: 5

Views: 36608

Answers (3)

Amir akbari
Amir akbari

Reputation: 62

(function($) {

  $('#edit-textbox').attr('placeholder','Your placeholder text');

})(jQuery);

Upvotes: 0

David Thomas
David Thomas

Reputation: 253328

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.

Upvotes: 11

Robyflc
Robyflc

Reputation: 1209

If you're using HTML5 (and you should) there's a native placeholder attribute.

<input type="text" value="" placeholder="My placeholder!" name="textbox" id="edit-textbox">

Edit

As you said you can't edit the HTML and have to use JS, this may help.

$('#edit-textbox').attr('placeholder', 'My placeholder!');

Once again, this is for HTML 5.

Upvotes: 4

Related Questions