August 17, 2024
JavaScript Confirm box
Confirm boxes are usually use to take confirmation from the user when some condition occur. For example suppose you have condition that you have two cars one is red and another is blue and you want to confirm with your friend that do you want to go by red or blue car. So such kind of situations also occurs in programming world. Whenever you want to take confirmation from your website's user about some situations then you can use confirm boxes. Confirm boxes usually have two buttons 'Ok' and 'Cancel'. Confirm box returns a value it return 1 if user clicks on 'Ok' button and it returns 0 if user clicks on 'Cancel' button. You can perform actions according to the value return by confirm box. Example of confirm boxes are mentioned below:
Code
<html>
<head>
<script language='JavaScript'>
function confirm_box_example() {
var value = confirm('Are you sure, you want to play cricket?');
if (value == 1){
alert('You are agree to play cricket.');
}
else
{
alert('You refused to play cricket.');
}
}
</script>
</head>
<body>
<form name='myForm' id='myForm' method='post'>
<input type='button' value='Play Cricket'
onclick='confirm_box_example();'>
</form>
</body>
</html>
In above mentioned example we have written a function with the name of 'confirm_box_example()' and called it on onClick event of a button. When you click on button then a confirm dialog box will appear on the screen with a question 'Are you sure, you want to play cricket?' and there would be two button there first is 'Cancel' and second is 'Ok'. If you click on ‘Ok’ button then confirm box will return 1 to value variable and if you click on 'Cancel' button then it will return 0 to value variable. After that we have written If conditional statement if value variable will have a 1 then it will show an alert with 'You are agree to play cricket' else there would an alert box with different message 'You refused to play cricket.'.