skip to Main Content

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

3

Answers


  1. Seems you are declaring ‘b’ variable inside the if block and trying to access it outside.

    Declare the variable before if as,

     let b = 0;
    

    Ex.,

     $('#praktijk').on('change', function() {
                let a = $('input[name="aantal"]').val() * $('input[name="lesprijs"]').val();
                let b = 0;
                var checked = $('#praktijk').is(':checked');
                console.log($('#praktijk').is(':checked'));                
                if ($('#praktijk').is(':checked')) {
                    b = Number($('input[name="examenprijs"]').val());
                }  
                let prijs = a + b;
                $('input[name="pakketprijs"]').val(prijs);
            });
    
    Login or Signup to reply.
  2. You need to define b variable out of the if.

    This is the corrected 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'));
            let b = 0;
            if ($('#praktijk').is(':checked')) {
                b = Number($('input[name="examenprijs"]').val());
            }
            let prijs = a + b;
            $('input[name="pakketprijs"]').val(prijs);
        });
    
    Login or Signup to reply.
  3. 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;
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search