1

I'm trying to insert price into the html element, which I'm getting from the input "data" value.

First function is working perfect, but second one is always giving 0.

$(document).ready(function() {

    if ($('input[name="bedrooms"]').is(':checked')) {
        var bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
    } else {
        var bedroomPrice = 0;
    }

    $('input').on('change', function() {
        $('#total').html(bedroomPrice);
    });

});

Could you please tell me what I'm doing wrong?

2
  • 3
    The first part only runs when page loads and nothing will change value of bedroomPrice after that Commented Nov 3, 2019 at 14:28
  • @charlietfl Thanks. How stupid from me Commented Nov 3, 2019 at 14:40

1 Answer 1

2

You are using assigning value to a variable only when page loads. Actually you need to update the value of the variable when your input is changed. Here is updated JS code:

$(document).ready(function() {
    var bedroomPrice = 0;
    $('input').on('change', function() {
        if ($('input[name="bedrooms"]').is(':checked')) {
            bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
        } else {
            bedroomPrice = 0;
        }
            $('#total').html(bedroomPrice);
    });
});

Now it checks bedroom prices when the input gets change, which is latest value.

Also if you have multiple bedrooms choices and you want to show only price of the checked checkbox (considering user can check any 1 checkbox only at the time). User this (which is the current element object) instead of input[name="bedrooms"]. So JS code will becomes like:

$(document).ready(function() {
    var bedroomPrice = 0;
    $('input').on('change', function() {
        if ($(this).is(':checked')) {
            bedroomPrice = $('input[name="bedrooms"]:checked').data('price');
        } else {
            bedroomPrice = 0;
        }
        $('#total').html(bedroomPrice);
    });
});

Hope it will work for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.