Ali Bahaari Ali Bahaari - 2 months ago 12
Javascript Question

How to access a variable inside a function in jQuery?

I had put some Radio Button for a Price List.
I have written this :

$(document).ready(function () {
$('#windowsRange input').on('change', function () {
var windowPrice = $('input[name=windowName]:checked', '#windowsRange').val();
});
$('#profilesRange input').on('change', function () {
var profilePrice = $('input[name=profileName]:checked', '#profilesRange').val();
});
$('#tapesRange input').on('change', function () {
var tapePrice = $('input[name=tapeName]:checked', '#tapesRange').val();
});
$('.totalPrice').html(windowPrice + profilePrice + tapePrice);
});


I can access these variable inside ON Method but I want to Plus all of them & put that in .totalPrice Class ...
Any way to do this ?
Thanks ...

Answer

You can simply make it "globally" vars

$(document).ready(function () {
    var windowPrice, profilePrice, tapePrice;
    $('#windowsRange input').on('change', function () {
        windowPrice = parseInt($('input[name=windowName]:checked', '#windowsRange').val());
        setTotal();
    });
    $('#profilesRange input').on('change', function () {
        profilePrice = parseInt($('input[name=profileName]:checked', '#profilesRange').val());
        setTotal();
    });
    $('#tapesRange input').on('change', function () {
        tapePrice = parseInt($('input[name=tapeName]:checked', '#tapesRange').val());
        setTotal();
    }); 
    function setTotal() {      
        $('.totalPrice').html(windowPrice + profilePrice + tapePrice);
    }
    setTotal();
});