neil
neil

Reputation: 1306

jQuery .append() to add required class to form elements

I'd like my HTML5 form to get an asterisk ('*') for a required field - I can add required as an attribute but the rest of the form output is a little cumbersome, due to the software we use.

I've got the following jQuery working, which looks for an attribute of required and then appends a <span> element.

$('*[required]').prev().append('<span class="required">*</span>');

I'm not experienced with jQuery so is this an efficient enough way to target a form with, say, 10 required elements? Or could it be improved, eg, is .appendTo() or .insertAfter() more appropriate?

Upvotes: 0

Views: 176

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272086

Assuming that your code is working and you are pondering:

so is this an efficient enough way to target a form with, say, 10 required elements?

* is very in-efficient selector; it matches everything. This means, for example, if your DOM has 1000 elements, the browser has to check all of them for the presence of required attribute. Be specific when possible:

$("input[required], select[required], textarea[required]")

Or could it be improved, e.g. .appendTo() or .insertAfter() more appropriate?

It depends on where the * is supposed to go. So use the function that makes sense.

Upvotes: 2

Jai
Jai

Reputation: 74738

You can do this to improve using .before():

$(':input[required]').before('<span class="required">*</span>');

Upvotes: 2

Oz Lodriguez
Oz Lodriguez

Reputation: 973

Its always expensive to manipulate the dom, but your method does do the trick. but I would do this with css selector, because technically it is a visual thing. If you are supporting older browser your method is fine. Here is a more simplified version

Just an example:

$('[required]').wrap('<span class="required">*</span>');

This will wrap the input in a span, but you can also wrap your prev element.

Upvotes: 0

Related Questions