how to add placeholder attributes in Silverstripe Userforms Module

to be honest i didn’t find a clean way yet, but i thought this workaround might be worth sharing.

…since SilverstripesUserforms Module Uses jQuery for Validation you can put these lines of code in your UserDefinedForm.ss Template:

jQuery(document).ready(function(){
jQuery('form label').each(function(){
jQuery(this).parent().find('input, textarea').attr('placeholder', jQuery(this).html());
jQuery(this).remove();
})
});

This will iterate over the labels in the form , build placeholder attributes from each one and then remove it.

If anyone knows a way how to do this in PHP, i’d appreciate a comment :)

5 Replies to “how to add placeholder attributes in Silverstripe Userforms Module”

  1. Thanks for the tips Max!

    I tried out your code, and found there was an issue with the labels for checkboxes disappearing. The other issue was that it was only working in modern browsers, so I found a nice function to test the browser’s compatibility, and then I found a plugin that works on all browsers!

    My workaround is as follows:

    function placeholderIsSupported() {
    test = document.createElement('input');
    return ('placeholder' in test);
    }
    jQuery(document).ready(function(){
    jQuery('form label').each(function(){
    if(jQuery(this).parent('.textarea, .text, .password, .type-text, .type-textarea').length == 1){
    if(placeholderIsSupported()){
    jQuery(this).parent().find('.text, textarea').attr('placeholder', jQuery(this).html());
    jQuery(this).remove();
    }else{
    convertLabel(jQuery(this));
    }
    }
    });
    

    Notes:
    I’m using this with SilverCart which has some non-standard classes (type-text and type-textarea).
    The convertLabel function uses this plugin:
    http://www.dhmedia.com.au/blog/nice-placeholders-jquery

    Hope this helps someone!

  2. This is nice but it’s true about checkbox text disappearing. For instance the “Remember me next time?” text for the checkbox on the login page disappears.
    It’s also a bit jumpy. I can see the label load outside before it’s removed and goes in as a placeholder.

    I played around with the .not(‘[type=checkbox]’) but couldn’t get it to work properly

Leave a Reply

Your email address will not be published. Required fields are marked *