How To Show Alert Using JavaScript

Alert Is Used To Show A Message To The User. It Has Generally A Text Which Contains The Message And A OK Button On Clicking Which Alert Gets Disappeared


Why To Use Alert

Alert Is Used To Show Any Important Message To The User. For Example There Is A Page With Login Form. If The Detail Entered By User Does Not Matches With The Original Details , Then We Can Show An Alert With Message That Your Entered Details Are Incorrect. Like That , Depending Upon The Situations And Requirements , Alert Is Shown

How To Show Alert In HTML

To Show An Alert In HTML , We Need To Use alert() Method Of JavaScript Which Is Used To Display An Alert Box Containing Message

Syntax Of Alert In JavaScript

To Show Alert In JavaScript , We Need To Enter The Message Inside The Round Bracket Of alert Method

alert('Hi There');
Now Lets Take Some Examples So That You Can Understand The Concept Of alert() In JavaScript Properly

Code Example Of alert() Method In JavaScript

Without Using Variable

Lets Take An Simple Example In Which We Will Show A Message Using alert() Method. For This , We Will Create A Button Upon Clicking Which A Function Will Be Called In Which alert() Method Is Present. Note That , We Will Not Use Variable In This Example To Store The Message

<script>
function showmsg()
{
alert('Hi There');
}
</script>
<button onClick='showmsg()'>Show Alert</button>


Using Variable

In This Example , We Will Store The Message Text In A Variable And Then Will Call It Using alert() Method

<script>
function showmsg()
{
var mymsg="Hi There";
alert(mymsg);
}
</script>
<button onClick='showmsg()'>Show Alert</button>


Output


In This Way , We Can Use alert() Method To Show An Alert To The User