Manu
Manu

Reputation: 1470

Alert with integrated global condition

I am new to JQuery/JavaScript and need a jump start for below case:

Notifications (alert messages) can be useful for new users but annoying to experienced users. So I want to give my users the option to show or not show these messages depending on user setting. In order not having to build the same condition (derived from the user setting) around every single alert, I would like to write a function that

I know how to build the condition around the alert, but fail to make it globally accessible:

var isConfirmActiv = "@UserPrincipal.ConfirmActiv";
var myMessage ="Bla bla";
if (isConfirmActiv.toLowerCase() === "true") {
    alert(myMessage);
}

I would like to use it in the script section of the view:

(var isConfirmActiv = "@UserPrincipal.ConfirmActiv";) ... somewhere?
myAlert("Bla bla", isConfirmActiv);

And in a script-file:

function myAlert(myMessage, isConfirmActiv){    
    if (isConfirmActiv.toLowerCase() === "true") {
    alert(myMessage);
    }
} 

Upvotes: 1

Views: 45

Answers (2)

Mohammad Fahmawi
Mohammad Fahmawi

Reputation: 195

You can create javascript file and name it Utility for example.

place your function and the global variable isConfirmActiv inside that file and link the js file to all views or to the master layout.

 var isConfirmActiv;

    function myAlert(myMessage, isConfirmActiv){    
        if (isConfirmActiv.toLowerCase() === "true") {
        alert(myMessage);
        }
    } 

- set directly the global defined isConfirmActiv value in every View in the script section (Note: don't redefine it, its already defined globally in javascript file)

    isConfirmActiv = "@UserPrincipal.ConfirmActiv";

- Now you can call the function from anywhere in your project.

    function myAlert(myMessage, isConfirmActiv){    
        if (isConfirmActiv.toLowerCase() === "true") {
            alert(myMessage);
        }
    } 

Upvotes: 1

Alexander
Alexander

Reputation: 73

You must define this var in the global scope (outside a function):

https://www.w3schools.com/js/js_scope.asp

For example:

 var isConfirmActiv = "@UserPrincipal.ConfirmActiv";
 function myAlert(string myMessage){        
        if (isConfirmActiv.toLowerCase() === "true") {
            return alert(myMessage);
        }
    }

Upvotes: 2

Related Questions