Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery if checkbox is checked malfunction

I’m having a bit strange problem, I have a form with a checkbox, where Jquery has to adjust values in an input field. But, when I check with console.log($('#praktijk').is(':checked')); I get a neat true or false answer, no problem there.
But when I put it in an if statement like this $('#praktijk').is(':checked') it doesn’t work, for some vague reason.
For more interpretation I’ll give the whole jscript code:

$('#praktijk').on('change', function() {
        let a = $('input[name="aantal"]').val() * $('input[name="lesprijs"]').val();
        var checked = $('#praktijk').is(':checked');
        console.log($('#praktijk').is(':checked'));
        if ($('#praktijk').is(':checked')) {
            let b = Number($('input[name="examenprijs"]').val());
        } else {
            let b = 0;
        }
        let prijs = a + b;
        $('input[name="pakketprijs"]').val(prijs);
    });

I’m really confused about this, and hope someone can help me.
Grts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you declare a variable inside an if or else block using let, it is only accessible within that block. In your code, you are declaring b inside the if and else blocks, and trying to use it outside those blocks.

...
let b = 0; // Declare b outside the if-else block

if ($('#praktijk').is(':checked')) {
    b = Number($('input[name="examenprijs"]').val());
}

let prijs = a + b;
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading