Use css to add asterisk * to required fields and clear it when not needed

北城余情 提交于 2021-01-27 13:12:20

问题


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 to no avail. So I have turned here to Stack Overflow! :)

Let me put the code and try to explain what I want to achieve.This is from a Kendo UI for MVC wrapper, so it has some Kendo classes but it shouldn't change anything.

This is what the wrapper code looks like when the page is first loaded (in the Chrome debug window). At this point, i.e. when the page is first loaded, I want to show the user the asterisk on all the required fields.

<div class="form-group">
    <label><b>Phone</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input required="required" data-val="true" data-val-required="The Phone field is required." id="PhoneNumber" >
    </div>
</div>

There's a validator defined as follows which dynamically adds/ removes error classes to the form elements.

var $validator = $("#form").validate({
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    unhighlight: function (element) {
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

So currently, when the user clicks on this field and loses focus, the code looks like this:

<div class="form-group has-error">
    <label><b>Phone</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input required="required" data-val="true" data-val-required="The Phone field is required." id="PhoneNumber" >
        <span for="PhoneNumber" class="help-block">This field is required.</span>
    </div>
</div>

So the div gets has-error class and a span is added to show the error message.

When we fulfil this requirement by typing something in this field, the error message is hidden and the error class is removed and has-success class added and the code looks like this:

<div class="form-group has-success">
    <label><b>Phone</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input required="required" data-val="true" data-val-required="The Phone field is required." id="PhoneNumber" >
        <span for="PhoneNumber" class="help-block" style="display: none;">This field is required.</span>
    </div>
</div>

So looking at this behavior of these elements, is there a way to find elements that have the 'required' attribute, go one step up to find their label and put a * after them. And when the form has no error class, removing that * again? I'm clueless to finding that kind of css selector! :(

I have done it using jQuery, it works, but I still don't like it as the form is so dynamic and I need to call this AstAdd() method whenever the elements' required attribute change. css way would have been way cleaner.

function AstAdd(){
    $('input[required]').each(function () {
        AstToggle($(this));
        $(this).blur(function () {
            AstToggle($(this));
        });
    });
}
function AstToggle(element) {
    if (element.val() == '') {
        element.closest(":has(label)").find('label').addClass('Asterisk');
    } else {
        element.closest(":has(label)").find('label').removeClass('Asterisk');
    }
}

And create a css class like this:

.Asterisk:after {
    content: " *";
    color: red;
}

Thank You very much for the help!


回答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>
  <span class="k-widget phonenumber">
        <input required="required" data-val="true" data-val-required="The Phone field is required." id="PhoneNumber" >
    </div>
</div>
<div class="form-group">
    <label><b>Mobile Number</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input id="MobileNumber" >
    </div>
</div>
<div class="form-group">
    <label><b>Office number</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input id="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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label><b>Phone Number</b></label>
  <div>
    <span class="k-widget phonenumber">
        <input required="required" data-val="true" data-val-required="The Phone field is required." id="PhoneNumber" >
    </div>
</div>
<div class="form-group">
    <label><b>Mobile Number</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input id="MobileNumber" >
    </div>
</div>
<div class="form-group">
    <label><b>Office number</b></label>
    <div>
        <span class="k-widget phonenumber">
        <input id="OfficeNumber" >
    </div>
</div>

Hope that helps.



来源:https://stackoverflow.com/questions/56587065/use-css-to-add-asterisk-to-required-fields-and-clear-it-when-not-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!