Majoros
Majoros

Reputation: 13

Add a custom CSS class with parsley.js

Using ParsleyJS, I have some custom javascript to add/remove a CSS class to an icon based on if the input is valid. Everything works, except when a user enters one input successfully and tabs/goes to the next input. When that happens, the class is applied to the icon even though the input is not valid.

See fiddle: https://jsfiddle.net/cfw80607/1/

JavaScript:

$('form').parsley().subscribe('parsley:field:validate', function (fieldInstance) {
    if ($('#name').parsley().isValid()) 
        $('.fa-user').addClass('cta-success').removeClass('cta-error');
    else
        $('.fa-user').addClass('cta-error').removeClass('cta-success');
    if ($('#email').parsley().isValid())
        $('.form-group .fa-envelope').addClass('cta-success').removeClass('cta-error');
    else
        $('.form-group .fa-envelope').addClass('cta-error').removeClass('cta-success');
});

Upvotes: 1

Views: 2363

Answers (2)

Timur
Timur

Reputation: 639

I think your want to use listeners on each field

$('form').parsley();

$.listen('parsley:field:error', function(ParsleyField) {
    ParsleyField.$element.prev('i.fa').removeClass('cta-success').addClass('cta-error');
});
$.listen('parsley:field:success', function(ParsleyField) {
    ParsleyField.$element.prev('i.fa').removeClass('cta-error').addClass("cta-success");    
});

Example here https://jsfiddle.net/acidrat/wqpr4gcq/

Upvotes: 1

Alan Files
Alan Files

Reputation: 318

Maybe you could use the focusout as well as the change. data-parsley-trigger="change focusout"

https://jsfiddle.net/cfw80607/2/

Upvotes: 0

Related Questions