McNavy McNavy - 2 months ago 7
jQuery Question

Variables - Other scripts - jQuery

Already, I'm newer on jQuery language.

So, this is my question :
How can i use a variable from a first script to another script in jQuery ?

The script 1 retrieve item selected from dropdown list :

Script 1 :

<script>
$('#ERDF').change(function codeterdf()
{
var codet_erdf = $('#ERDF option:selected').first().attr('value');

// Display on input named "pu"
// $('#pu').val(codet_erdf);

});
</script>


And my second script, it will be to check if var "codet_erdf" is defined or not with "undefined".
PS : The second script will be execute only when the button is clicked.

Script 2 :

<script>
$(document).ready(function(){
$("button").click(function(){
if (typeof codet_erdf == 'undefined') {
$("p").text("Codet ERDF non choisi");
}
else
{
$("p").val(codet_erdf);
}
}
};
</script>

Answer

In script-1 you have to declare global variable(outside of function).

Script-1

<script>
var codet_erdf='';
  $('#ERDF').change(function codeterdf() {
    codet_erdf = $('#ERDF option:selected').first().attr('value');

// Display on input named "pu"
// $('#pu').val(codet_erdf);

});
</script>`

Script-2

<script>
    $(document).ready(function(){
        $("button").click(function(){
            if (codet_erdf == '') {
                $("p").text("Codet ERDF non choisi");
            }
            else
            {
                $("p").val(codet_erdf);
            }
        }
    };
    </script>
Comments