Mathematical calculations in real time through the onchange event in javascript

0

I have a select element configured in a form with a number of options, depending on the selected option, some values are brought via ajax of the database and with the following function it makes the comparison of the values of that data.

var probar = function(event){

        //event.preventdefault();

        var a_cilindro = parseFloat($('#a_cilindro').val());
        var a_bobina = parseFloat($('#a_bobina').val());

        if(a_cilindro<a_bobina){
            alert('Error: El valor del cilindro en menor al de la bobina');
            $('#a_cilindro ').addClass("uk-form-danger");
            $('#a_cilindro ').removeClass("uk-form-success");
        } else {
            $('#a_cilindro ').removeClass("uk-form-danger");
            $('#a_cilindro ').addClass("uk-form-success");
};

    var select = document.getElementById('my_select');
    select.addEventListener('change', probar);

The problem is that this comparison of the data does not make me in real time but after I select another option of the select, that is, if the result meets the condition (a_cilindro<a_bobina) marks me the input with class uk-form-success when I should show the error alert immediately and mark it with the class uk-form-danger , but if I select an option that does not meet the condition there if it shows me the error alert based on the data of the previous selection and marks me the correct data with class uk-form-danger when you should not show me an error and mark that field with class uk-form-success .

It is somewhat confusing but I hope you can understand, in these cases, how could you handle such events?

    
asked by Darwin Gomez 01.12.2017 в 07:06
source

1 answer

0

Let's see if I understood:

so that the comparison runs as soon as you load the page, you can use the following:

//apenas cargue la pagina llama a la funcion;
$(document).ready(probar);

//O tambien puedes

//llamar a la funcion cuando cargue la ventana
$(window).load(probar);

Now for you to call when you change the value of select you can put the following:

 $('#my_select').change(probar);
    
answered by 01.12.2017 в 21:25