Sergi Khizanishvili
Sergi Khizanishvili

Reputation: 587

Insert variable into the HTML from the input data attribute

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?

Upvotes: 1

Views: 71

Answers (1)

sssurii
sssurii

Reputation: 830

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.

Upvotes: 2

Related Questions