Skip to content Skip to sidebar Skip to footer

Use Css To Add Asterisk * To Required Fields And Clear It When Not Needed

I have an app that has gazillions of fields where some are are 'required' and some aren't and doing it using jQuery seems performance intensive. So I tried doing it using css but t

Solution 1:

Can sort of do this with CSS using Psuedo Elements and content.

input[required] {
  display: block;
}

input[required]::after {
  content: '*';
  color: red;
}
<label><b>Phone Number</b></label><div><spanclass="k-widget phonenumber"><inputrequired="required"data-val="true"data-val-required="The Phone field is required."id="PhoneNumber" ></div></div><divclass="form-group"><label><b>Mobile Number</b></label><div><spanclass="k-widget phonenumber"><inputid="MobileNumber" ></div></div><divclass="form-group"><label><b>Office number</b></label><div><spanclass="k-widget phonenumber"><inputid="OfficeNumber" ></div></div>

It looks like there is a bug of sorts for this. See more: Combine CSS Attribute and Pseudo-Element Selectors?

I would strongly advise using jQuery as it it allows a lot more options.

$(function() {
  $("[required]").after($("<span>", {
    class: "required"
  }).html("*"));
});
.required {
  color: red;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="form-group"><label><b>Phone Number</b></label><div><spanclass="k-widget phonenumber"><inputrequired="required"data-val="true"data-val-required="The Phone field is required."id="PhoneNumber" ></div></div><divclass="form-group"><label><b>Mobile Number</b></label><div><spanclass="k-widget phonenumber"><inputid="MobileNumber" ></div></div><divclass="form-group"><label><b>Office number</b></label><div><spanclass="k-widget phonenumber"><inputid="OfficeNumber" ></div></div>

Hope that helps.

Post a Comment for "Use Css To Add Asterisk * To Required Fields And Clear It When Not Needed"