Checkbox with Function

Asked

Viewed 39 times

1

Good afternoon, I’m putting together a form with checkboxes that call a function through the onclick

<body> 
    <form name="questao1" method="post" onsubmit="sendToDB();"> 
        <br><input type="checkbox" name="Q1[]" value="Enfermagem" onclick="getPontos(1)"> Garantir a saúde das pessoas 
        <br><input type="checkbox" name="Q1[]" value="Eletroeletronica" onclick="getPontos(2)"> Máquinas e instalações elétricas.
        <br><br><input type="submit" value="Próximo" onclick="finalizar()">     
    </form>
</body>

To perform this function:

    function getPontos(pontos){

                efmg = 0;
                eltelt = 0;
                info = 0;
                alm = 0;
                pltc = 0;
                log = 0;
                adm = 0;
                qmc = 0;
                ma = 0;

                if (pontos == 1){ efmg = efmg + 1; }   
                if (pontos == 2){ eltelt = eltelt +1; }

}

function finalizar(){   
           if(efmg>eltelt){alert('Enfermagem');}else{alert('Eletroeletronica');} 
        }

However, every time I call this function the values return to zero, and I need the value to be maintained for the click of the next checkbox. the problem, is that if I do not assign the initial values as zero, the function does not work, and the finish does not show any result. Can someone help me solve it? I thank you in advance :)

1 answer

1


Use global variables, outside of your function, that initialize as 0 when the page is loaded, and each time the function is called they modify the value of these variables.

var efmg = 0;
var eltelt = 0;
var info = 0;
var alm = 0;
var pltc = 0;
var log = 0;
var adm = 0;
var qmc = 0;
var ma = 0;

function getPontos(pontos){

            if (pontos == 1){ efmg = efmg + 1; }   
            if (pontos == 2){ eltelt = eltelt +1; }

}

function finalizar(){   
       if(efmg>eltelt {alert('Enfermagem');}else{alert('Eletroeletronica');} 
    }

Something that occurred to me when I was seeing it too, You’re not initiating the variables within the function (var xxx, var yyy), so I imagine you do it somewhere else in the code, you can initialize like 0 right there.

  • Ook, I did this, but it still doesn’t work, I believe the error is now in the part of php Xp:

  • But you understood what was wrong ne? If you have more doubts in PHP, I recommend you create another topic.

  • Yes, thank you :)

  • @Rafazanezi if this answer solved your initial question, mark it as a solution in the left corner.

Browser other questions tagged

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