Search code examples
jqueryvariablesgloballocalvar

Using Local variable value's in Jquery


i'v got this functions at my script:

(document).ready(function () {
$(".plcardFirst").change(function() {
valueFirst = $( ".plcardFirst" ).val();
        });
$(".plcardSecond").change(function() {
valueSecond = $( ".plcardSecond" ).val();
    });
});

How can i use valueFirst and valueSecond values to calculate and run an if statement? many thanks


Solution

  • Note that javascript have function scope and not block scope which means variables declared inside a function with the keyword var can be used inside that function only. But here you are declaring valueFirst and valueSecond without the keyword var, so they are both considered as a global variables so you can access them anytime you want and anywhere even inside an if statement

    You can also use this way:

    $(document).ready(function () {
    var valueFirst,valueSecond; // declaring both variables at the beginning after document.ready
    
    $(".plcardFirst").change(function() {
    valueFirst = $( ".plcardFirst" ).val();
            });
    $(".plcardSecond").change(function() {
    valueSecond = $( ".plcardSecond" ).val();
        });
    
    // now you can use valueFirst and valueSecond of course if $( ".plcardFirst" ).val() and $( ".plcardSecond" ).val(); return something
    
    //example if(valueFirst == valueSecond){alert('both values are equal ');}
    });