using jquery to add an asterisk to all form fields with data-required=true

Klaaz picture Klaaz · Sep 3, 2013 · Viewed 8.8k times · Source

I was using this to add a asterisk from the fontawesome library to all form fields who had 'required' as a pseudo element (in a Twitter bootstrap form):

Field example:

<input type="text" name="firstname" 
    data-required="true" 
    data-error-message="Please enter your firstname" /> 

jQuery:

$(":required")
    .closest(".control-group")
    .children("label")
    .prepend("<i class='icon-asterisk'></i> ");

This works fine but I now moved to parsley.js to validate my form inputs. Parsley uses data-required='true' as a pseude element. I am not really into pseudo selectors right now. How do I change my jquery to do the trick again?

Answer

Will picture Will · Sep 3, 2013

This might work.

$( 'input[data-required="true"]' )
        .closest(".control-group")
        .children("label")
        .prepend("<i class='icon-asterisk'></i> ");

Link to the Documentation.