marcuthh
marcuthh

Reputation: 596

jQuery - toggle text displayed on label, depending on field input

I have an HTML <form> that I'm trying to validate using jQuery. So far I have it so that if a required field is left blank, some text is appended to the field's associated label informing the user. This is done like so:

    $(requiredInputs).on('blur', function(){
        //isolate name attribute of field left
        var fieldname = $(this).attr('name');
        //use name value to find associated label to field
        var label = $("#registration label[for='"+fieldname+"']");
        //sanitize and store current input value in variable
        var inputValue = $.trim($(this).val());
        if (inputValue.length === 0){
            //new div to be appended to the label
            var alert = '<p><small>This is a required field!</small></p>';
            //change HTML to inform user
            $(label).html(label.html() + alert);
            //emphasise input box
            $(this).css('border', '2px solid red');
        }
    });

I also have an event that removes the red border as soon as some text is input:

    //turn field back to normal on text entry
    $(requiredInputs).on('input', function(){
        //de-emphasise input box
        $(this).css('border', 'none');
    });

What I want to add into this event is to get rid of the 'required field' message at the same time, returning the label to just its original text. I don't know how best to go about this, as the label.html() value has been changed from its original state when the warning is added. Can this be done using a toggle function of some sort?

Thanks in advance, Mark

Upvotes: 2

Views: 609

Answers (2)

oshell
oshell

Reputation: 9103

There are several ways to solve this. You could use data attributes to toggle the text as mentioned, so I want to give you another solution.

Instead of changing the label you could give it a class which uses a pseudo element. Consequently you simply have to remove the class later.

jsfiddle

HTML

<form>
  <label for="foo" class="required">foo</label>
  <input type="text" id="foo">
</form>

jQuery

$('#foo').on('blur', function(){
    var inputValue = $.trim($(this).val());
    if (inputValue.length == 0){
        $('label').addClass('required');
    }
});

$('#foo').on('input', function(){
    var inputValue = $.trim($(this).val());
    if (inputValue.length > 0){
        $('label').removeClass('required');
    }
});

CSS

label.required::after { 
    content: " - required";
}

Upvotes: 1

Roman Hutnyk
Roman Hutnyk

Reputation: 1549

Save original text to some attribute on blur:

 $(label).attr('data-original', label.html());
 $(label).html(label.html() + alert);

Then restore it on input:

var fieldname = $(this).attr('name');
var label = $("#registration label[for='"+fieldname+"']");     
$(label).html($(label).attr('data-original'));

Upvotes: 1

Related Questions