How to convert jQuery’s . on function to pure Javascript

Asked

Viewed 561 times

4

Today I started trying to turn a function I’m using into jQuery (which @José helped me implement in this answer) to .on, for pure Javascript, but I’m facing some difficulties. The online courses I have already done have not addressed this aspect, so if the solution were accompanied by a good explanation would be ideal.

The code in jQuery is this:

$('.checar').on('validation', function(evt, valid) {
    var validou = document.getElementById('validou').value = valid ? "true" : "false";

    if (validou === "true") {
        $('#startBtnseg').removeAttr('disabled');
    }
});

This code validates a date, using the parameters returned by form.validator, and if the date is validated, it removes the disabled of button.

I’m trying to use addEventListener(), but it’s not working.

I made a FIDDLE to demonstrate the problem, and just remove jQuery (delete or comment) to see that the pure Javascript starts to enable the button normally, but if jQuery is along, then it doesn’t work.

I don’t need it to use class ('check'), because I want to use this script in conjunction with another, which has already been working for the same thing (remove the disabled from the same button), this one in pure Javascript (which I adapted from the script @Sérgio wrote in this answer).

Separately the two scripts work perfectly, but when the two are present, the pure javascript makes no difference, and if validates the jQuery code, then it opens the button (no matter that the condition of pure Javascript is not met).

I want to "merge" these two scripts, but I would also like to understand the process of converting the function to pure Javascript, if possible.

The pure Javascript code of the other validation:

var datainicial = document.getElementById('Cinsem');
var datafinal = document.getElementById('Cdesl22');

function formatar(mascara, documento) {
    var i = documento.value.length;
    var saida = mascara.substring(0, 1);
    var texto = mascara.substring(i);
    if (texto.substring(0, 1) != saida) {
        documento.value += texto.substring(0, 1);
    }
    verificar();
}

function gerarData(str) {
    var partes = str.split("/");
    return new Date(partes[2], partes[1] - 1, partes[0]);
}

function verificar() {
    var inicio = datainicial.value;
    var fim = datafinal.value;

    if (inicio.length != 10 || fim.length != 10) {
        return;
    }
    if (gerarData(fim) >= gerarData(inicio)) {
        $('#startBtnseg').removeAttr('disabled', 'disabled');
    }
}

1 answer

4


Normally convert from on for native Javascript is simple - for each event handled by on (ex.: click, blur, keyup) there is a corresponding native functionality (eg.: onclick, onblur, onkeyup); can then assign a handling function (Handler) to the desired elements (or to some common ancestor of them, in the spirit of the function on) or use addEventListener, as suggested in the question itself.

However, this validate implemented by the plugin form.validator does not have a native correspondent that can easily be called [as far as I know]. To implement an equivalent functionality, just seeing what the plugin does (perhaps studying your source code) and doing the same or similar. So I don’t have an answer for you on this case.

However, if it is just to ensure that both checks (format and custom logic) are done, one can find a way. I do not know the form.validator with details, so I don’t know the best way to do this (I’m sure there’s something in the API to help you). But one way - not at all "polished", though - is to modify your formatar to activate (Trigger) programmatically the validate, and in the validate itself call your method verificar:

on('validation', function (evt, valid) {
    var validou =  document.getElementById('validou').value = valid ? "true" : "false";

    if (validou === "true") {
        verificar(); // Chama o verificar também, em vez de liberar o botão
    }
});

...

function formatar(mascara, documento) {
    var i = documento.value.length;
    var saida = mascara.substring(0, 1);
    var texto = mascara.substring(i);
    if (texto.substring(0, 1) != saida) {
        documento.value += texto.substring(0, 1);
    }
    $(documento).validate(); // trigger no validate
}

The result is that the button will only become enabled when both conditions are met. Example in jsFiddle.

  • 1

    Wow, great answer! The first and third objectives (doing both validations and LEARNING IN THE PROCESS) are satisfied! : -) From what you explained is not the best practice, so I’ll hold on to not click on the solved :-), and leave open for now, will appear someone to contribute even more right. Thanks a lot man! Great success for you! Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.