something like confirm("Are U sure?") JavaScript - javascript

I use
string js = #" return confirm('Are you sure you want to do this?');";
myAspButton.OnClientClick = js;
event rises after "OK" clicking and nothing happen after "Cancel"
I want to create my custom modal, but server event fired before any button click!
how to implement my own function like confirm(Are you sure you want to do this?') which returns value after button click?
my code:
string js = #"dialog('Are you sure you want to do this?',
function() {
return true;
},
function() {
return false;
}
);";
myAspButton.OnClientClick = js;
JS code:
function dialog(message, yesCallback, noCallback) {
$('.title').html(message);
var dialog = $('#modal_dialog').dialog();
$('#btnYes').click(function() {
dialog.dialog('close');
yesCallback();
});
$('#btnNo').click(function() {
dialog.dialog('close');
noCallback();
});
}
HTML code:
<div id='modal_dialog'>
<div class='title'>
</div>
<input type='button' value='yes' id='btnYes' />
<input type='button' value='no' id='btnNo' />

There's some modifications to make on your code...
You cannot bind a click event many times on the same element or it will trigger many times, so first you need to remove the bind to add it again with another callback.
Also, you can make an "overlay", that covers the entire page until some button is clicked. See the css part to take a look on what I did.
See the example below and check if this it's something you need.
$("#dialogBtn").on("click", dialog.bind(this, 'Are you Sure?', yesCallback, noCallback));
function dialog(message, yesCallback, noCallback) {
var modal = $("#modal_dialog");
modal.show();
$('.title').html(message);
$('#dialogBtnYes').off("click").on("click", function() {
modal.hide()
yesCallback.call();
});
$('#dialogBtnNo').off("click").on("click", function() {
modal.hide()
noCallback.call();
});
}
function yesCallback(){
console.log("YES");
}
function noCallback(){
console.log("NO");
}
#modal_dialog{
display: none;
width: 100%;
height: 100vh;
background-color: rgba(0,0,0, 0.1);
z-index: 1000;
position: absolute;
top: 0;
left: 0;
}
#modal-content{
padding: 12px;
border: 1px solid;
box-shadow: 1px 1px 3px black;
background-color: #fff;
margin: auto;
position: relative;
width: 50%;
top: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Dialog' id="dialogBtn"/>
<div id='modal_dialog'>
<div id="modal-content">
<div class='title'></div>
<input type='button' value='yes' id='dialogBtnYes' />
<input type='button' value='no' id='dialogBtnNo' />
</div>
</div>

Related

unbind the initial click function on another button click

I have a form which is initially hidden.
There is two steps of click flow to reach the form. I need to reset the initial click action when the form close button is clicked.
Adding the sample code and demo.
Here goes the flow
Click on the Join Now text
Then click on the text Click here to open the form text
Then click on the close icon
There comes the pop up
What I now need to know is,
By clicking on Yes , the form needs to be reset and the screen should look like how it looked initially (Brand name box with join now text) and the initial click action of join now should be refreshed.
By clicking on No, it should remain on the same form.
$(".button").click(function(e){
e.preventDefault();
$(this).hide();
$(".slidethis").fadeIn(800).css("display","inline-block");
$(".wrapper").css("display","block");
});
$(".seconddiv").hide();
//forstdiv click
$(".firstdiv").click(function(){
$(this).hide();
$(".seconddiv").show();
});
//Close button
$(".close_icon").click(function(){
$(".popup").show();
});
Demo Here
P.S: I don't want to refresh the page by closing the form.
Adding this code should do it. It's about reversing your steps:
$("input[value=Yes]").click(function(){
//reset - reverse all the steps
$(".button").show();
$(".slidethis").fadeOut(800).css("display","none");
$(".wrapper").css("display","inline-block");
$(".popup").hide();
$(".seconddiv").hide();
$(".firstdiv").show();
});
$("input[value=No]").click(function(){
$(".popup").hide();
});
Updated fiddle: https://jsfiddle.net/5353ntuf/5/
Working fiddle.
You should add an event click on the both buttons Yes and No, so give them a common class , e.g confirm class:
<input type="button" class='confirm' value="Yes" />
<input type="button" class='confirm' value="No" />
Then add a condition to check which action you're going to perform, like :
//Confirm buttons
$("body").on("click", ".confirm", function() {
$(".popup").hide();
if ($(this).val() == 'No')
{
$('form input').val(""); //Reset form
} else {
$(".seconddiv,.slidethis").hide();
$(".firstdiv,.button").show();
$(".wrapper").css("display", "inline-block");
}
});
Hope this helps.
//slide open the main panel
$(".button").click(function(e) {
e.preventDefault();
$(this).hide();
$(".slidethis").fadeIn(800).css("display", "inline-block");
$(".wrapper").css("display", "block");
});
$(".seconddiv").hide();
//forstdiv click
$(".firstdiv").click(function() {
$(this).hide();
$(".seconddiv").show();
});
//Close button
$(".close_icon").click(function() {
$(".popup").show();
});
//Confirm buttons
$("body").on("click", ".confirm", function() {
$(".popup").hide();
if ($(this).val() == 'No') {
$('form input').val("");
} else {
$(".seconddiv,.slidethis").hide();
$(".firstdiv,.button").show();
$(".wrapper").css("display", "inline-block");
}
});
.wrapper {
background: #9ac366;
display: inline-block;
}
.headcard {
display: inline-block;
text-align: center;
padding: 3% 30px;
float: left;
}
.slidethis {
background: #b67fd8;
padding: 20px 0;
width: 70%;
vertical-align: top;
position: relative;
height: 228px;
display: none;
position: relative
}
.firstdiv,
.seconddiv {
width: 200px;
border: #888 solid 2px;
padding: 20px;
}
.close_icon {
background: #333;
color: #fff;
padding: 4px;
float: right;
margin-top: -20px;
text-decoration: none
}
.popup {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
background: #e4e4e4;
text-align: center;
padding-top: 5%;
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="headcard">
<h4>Brand Name</h4>
Join Now
</div>
<!--this is hidden by default-->
<div class="slidethis">
<div class="firstdiv">
Click here to open the form
</div>
<div class="seconddiv">
<form>
X
<input placeholder="name" />
<input placeholder="email" />
</form>
<!--close pop up-->
<div class="popup">
Closing will clear the form data. Do you want ot close?
<br/>
<input type="button" class='confirm' value="Yes" />
<input type="button" class='confirm' value="No" />
</div>
</div>
</div>
</div>

How to change the background color of an input field when text is entered?

I'm pretty new with Javascript and jQuery, and can't seem to indentify the reason why my code acts like it does.
I have created two seemingly identical functions to change the background color of an input field.
Their goal is to turn the background color of the given input field to the color #00FF7F if anything is typed in the field. And if not, the field should be transparent.
Code JS:
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
css:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
Simple HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<!-- Stylesheet link -->
<link rel="stylesheet" type="text/css" href="assets/style.css">
<!-- jQuery link -->
<script type="text/javascript" src="assets/vendor/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<!-- Javascript link-->
<script type="text/javascript" src="assets/js/javascript.js"></script>
</body>
On the jsbin above, try typing in both the Username and Password field to see how they react differently.
Images of what happens. Didn't want to include all images here:
http://imgur.com/a/qgubP
I realize there probably is a way to compromise my js/jquery into 1 function that each input field calls instead of have a function for each.
If both of these fields are required, here's a much simpler solution using CSS only.
Add the attribute required to your <input> tags and then use the pseudo-class :valid.
.form-control:valid {
background-color: #00FF7F;
}
Code snippet:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
.form-control:valid {
background-color: #00FF7F;
}
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username" required>
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
jsFiddle : https://jsfiddle.net/7vzjz2u5/3/
jQuery
$(document).ready(function() {
$('.change-background').on('change', function() {
var $this = $(this);
var value = $.trim($this.val());
// toggleClass can be provided a bool value,
// If we provide true we add class, if false we remove class
$this.toggleClass('filled-background', value.length !== 0);
}).change();
// We also want to call a 'change' event on
// all inputs with the change-background class just incase the page has
// pre-filled in values
});
Instead of listening for the keyup event and then running a function, just create a listener on the change event, also if we just apply one class to all inputs we want the background colour to change on, we can just create one listener which will do it for any input with the class change-background.
Html
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="change-background form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="change-background form-control" placeholder="Password">
</div>
</div>
Css (the extra class for background color)
.filled-background {
background-color: #00FF7F;
}
Also side note
listening for keyup is back, someone may want to copy and paste their username and password and if they do this it won't trigger an keyup event if they use right click and paste.
Your code clears the background color when the length is 0. The way it checks the length is with this snippet of code:
var value = $.trim($(".form-control").val());
The selector $(".form-control") will select all elements with the CSS class of .form-control. This is a problem because there is more than one of them; in this case, it will always return the value from the first element found.
You should change the code to check for the specific control by searching by ID, like so:
var value = $.trim($("#logindata1 input").val()); //get user ID
var value = $.trim($("#logindata2 input").val()); //get password
You have some minor mistakes, but no worry. We can fix it.
First Problem
Other answers are pointing something important: you are trying to get the value selecting all elements with form-control class.
var value = $.trim($(".form-control").val());
You can do it, replacing your selector by your already declared variables $input1 and $input2. This way:
var value = $.trim($input1.val());
var value = $.trim($input2.val());
Second
Ok. First problem solved. The second problem is in your second function. You trying to set an invalid css: $input2.css("#background-color", "transparent");
When should be: $input2.css("background-color", "transparent"); (without #).
Next One
Nice. Next one. The id's you are setting logindata1 and logindata2 are on your divs. So, you are wrongly trying to get the value of the div instead the value of the input. you can fix your selector by appending input, this way:
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
Finally
So, finally, it should work:
$(document).ready(function () {
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
function onChangeInput1() {
$input1.css("background-color", "#00007F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00007F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
Your value check is not right. With your jQuery, you are checking the value of both inputs every time.
Try checking the single inputs that you are interested in instead.
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});

How to take back a page to its previous state by clicking the back button of the browser in javascript

I have a page with a link to a form. After clicking the link the form shows up and the link disappears. The problem that i have is, when i click the browser's back button, the values of the URL is changed, but the state of the page doesn't go back to previous state. The form should disappear and the link shows back. Also on reload when the form is visible, the page goes back to its first state, which i need to prevent from happening.
Code :
<html>
<style>
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
</style>
<body>
<div id="categContainer1">
<div class="titimmo">Real Estate</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made"/>
<h4>Price :</h4>
<input type="text" name="modele"/><br/><br/>
</form>
</div>
<script>
function stepone() {
document.getElementById('a_categ').onclick = function () {
document.getElementById('categContainer1').className += " hidden";
document.getElementById('formContainer').className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
return false
};
}
stepone();
</script>
</body>
</html>
First question is: How to bring back the page to its previous state by clicking the browser's back button?
Second question is: How to prevent the page from going back to its previous state - on reload when it's on second state (when form is visible)?
There are two things you need to do to make it work:
To monitor browser back button click, use
window.onpopstate
method
To remember the form state, you need to store the value in
localStorage or in a cookie.
This is a basic example:
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
var formVisible = localStorage.formVisible || false;
var cContainer = document.getElementById('categContainer1');
var fContainer = document.getElementById('formContainer');
function formOpen(e) {
cContainer.className = "hidden";
fContainer.className = "visible";
window.history.pushState('Form', 'My form', this.getAttribute("href"));
localStorage.formVisible = 'Y';
return false;
};
function formClose(e) {
cContainer.className = "visible";
fContainer.className = "hidden";
localStorage.removeItem( 'formVisible' );
};
if( formVisible ) formOpen();
document.getElementById('a_categ').onclick = formOpen;
window.onpopstate = formClose;
.titimmo {
text-align: center;
padding: 10px;
font-size: 14pt;
background-color: #CC3300;
display: block;
}
.hidden {
display: none;
}
.visible {
display: block;
}
#formContainer {
padding: 1em 0 1em 2em;
background-color: #E8E8E8;
margin: 1em 0 1em 2em;
width: 88.9%;
}
#formContainer h4 {
color: #FF3300;
}
<div id="categContainer1">
<div class="titimmo">
Real Estate
</div>
</div>
<div id="formContainer" class="hidden">
<form action="add.php" method="post">
<h4>Location :</h4>
<input type="text" name="made" />
<h4>Price :</h4>
<input type="text" name="modele" />
</form>
</div>
Also on Fiddle, where you can actually see how it works.

Fetching input box value on submit button click

I am working on a game using ImpactJS engine and I have created a basic form for my game which contains input box and a submit button. I am able to retrieve values from the input box but what I want is that when the player clicks on submit whatever value is there in the input box gets fetched and I should be able to get that value on Submit click. If the value is null I should get an alert saying "no value or whatever". I want to use this final value and assign it to a variable that I can use in my JavaScript files inside the Impact engine to keep a track of the input from within the game. I am new to HTML, CSS in general so I have no clue how to achieve this.
Below is my HTML/CSS code that has an input box and a submit button.
<!DOCTYPE html>
<html>
<head>
<title>Impact Game</title>
<style type="text/css">
html,body {
background-color: #333;
color: #fff;
font-family: helvetica, arial, sans-serif;
margin: 0;
padding: 0;
font-size: 12pt;
}
#problemform {
display: none;
width: 300px;
height: 100px;
}
#probleminput {
position: absolute;
display: none;
top: 450px;
left: 240px;
height: 50px;
width: 350px;
}
#problemsubmit {
position: absolute;
display: none;
top: 530px;
left: 623px;
height: 40px;
width: 100px;
padding: 5px 10px 8px 2px;
}
#prob_submit_msg {
width: 30%;
margin-left: auto;
margin-right: auto;
text-align: center;
}
#canvaswrapper {
position: relative;
height: 768px;
width: 1024px;
display: block;
margin: auto;
margin-top: 80px;
vertical-align: middle;
}
#canvas {
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
<script type="text/javascript" src="lib/jquery.min.js"></script>
<script type="text/javascript" src="lib/impact/impact.js"></script>
<script type="text/javascript" src="lib/game/main.js"></script>
</head>
<body>
<div id="canvaswrapper">
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="problemform" class="form-inline">
<input id="probleminput" class="form-inline" type="text" style="display: inline;"></input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
</div>
<div id ="prob_submit_mssg" style="display: block;"></div>
</div>
</body>
</html>
Below is my block of code in ImpactJS in a different JS file to display the input box and submit button using Jquery
ProblemDisplay:function() {
this.setQuestion('This is a title','this is where the body will go and it will be super long and impossible to read or understand.', 'This is a hint');
this.isActive = true;
var form = $("#problemform");
var inputBox = $("#probleminput");
var submitButton = $("#problemsubmit");
form.show();
inputBox.show();
submitButton.show();
},
This is what I have working for now. But now I want the string passed in the input box to be stored in a different variable when clicking the submit button. How to achieve this?
Thanks!
Create an event listener for a click on the submit button.
In jQuery:
$('#submit-button').on('click', function() {
});
In vanilla js
document.getElementById('submit-button').addEventListener('click', function() {
});
Then get the value from the input box:
In jQuery:
$('#submit-button').on('click', function() {
var value = $('input').val();
// Do what you want with the value
});
In vanilla js
document.getElementById('submit-button').addEventListener('click', function() {
var value = document.getElementById('input').value;
// Do what you want with the value
});
Try With this.. :
html:
<input id="probleminput" class="form-inline" type="text" style="display: inline;"> </input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
<a id='testop' ></a>
Js:
var form = $("#problemform");
var inputBox = $("#probleminput");
var submitButton = $("#problemsubmit");
submitButton.click(function(){
var getval = ($("#probleminput").val()?$("#probleminput").val():alert('please fill the text field'))
$('#testop').text(getval);
});
Complete DEMO
If all you need is the value of the input field when someone clicks on the button, then this solution may work for you:
Fiddle Demo
JS:
$('#problemsubmit').on('click', function (event) {
event.preventDefault();
var formInput = $('#probleminput').val();
});

How to create a dialog with “Ok” and “Cancel” options

I am going to make a button to take an action and save the data into a database.
Once the user clicks on the button, I want a JavaScript alert to offer “yes” and “cancel” options. If the user selects “yes”, the data will be inserted into the database, otherwise no action will be taken.
How do I display such a dialog?
You’re probably looking for confirm(), which displays a prompt and returns true or false based on what the user decided:
if (confirm('Are you sure you want to save this thing into the database?')) {
// Save it!
console.log('Thing was saved to the database.');
} else {
// Do nothing!
console.log('Thing was not saved to the database.');
}
var answer = window.confirm("Save data?");
if (answer) {
//some code
}
else {
//some code
}
Use window.confirm instead of alert. This is the easiest way to achieve that functionality.
How to do this using 'inline' JavaScript:
<form action="http://www.google.com/search">
<input type="text" name="q" />
<input type="submit" value="Go"
onclick="return confirm('Are you sure you want to search Google?')"
/>
</form>
Avoid inline JavaScript - changing the behaviour would mean editing every instance of the code, and it isn’t pretty!
A much cleaner way is to use a data attribute on the element, such as data-confirm="Your message here". My code below supports the following actions, including dynamically-generated elements:
a and button clicks
form submits
option selects
jQuery:
$(document).on('click', ':not(form)[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('submit', 'form[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('input', 'select', function(e){
var msg = $(this).children('option:selected').data('confirm');
if(msg != undefined && !confirm(msg)){
$(this)[0].selectedIndex = 0;
}
});
HTML:
<!-- hyperlink example -->
Anchor
<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>
<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
<button type="submit">Submit</button>
</form>
<!-- select option example -->
<select>
<option>Select an option:</option>
<option data-confirm="Are you want to select this option?">Here</option>
</select>
JSFiddle demo
You have to create a custom confirmBox. It is not possible to change the buttons in the dialog displayed by the confirm function.
jQuery confirmBox
See this example: https://jsfiddle.net/kevalbhatt18/6uauqLn6/
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// Do nothing
});
Pure JavaScript confirmBox
Example: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/127/
<div id="id_confrmdiv">confirmation
<button id="id_truebtn">Yes</button>
<button id="id_falsebtn">No</button>
</div>
<button onclick="doSomething()">submit</button>
Script
<script>
function doSomething(){
document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line
document.getElementById('id_truebtn').onclick = function(){
// Do your delete operation
alert('true');
};
document.getElementById('id_falsebtn').onclick = function(){
alert('false');
return false;
};
}
</script>
CSS
body { font-family: sans-serif; }
#id_confrmdiv
{
display: none;
background-color: #eee;
border-radius: 5px;
border: 1px solid #aaa;
position: fixed;
width: 300px;
left: 50%;
margin-left: -150px;
padding: 6px 8px 8px;
box-sizing: border-box;
text-align: center;
}
#id_confrmdiv button {
background-color: #ccc;
display: inline-block;
border-radius: 3px;
border: 1px solid #aaa;
padding: 2px;
text-align: center;
width: 80px;
cursor: pointer;
}
#id_confrmdiv .button:hover
{
background-color: #ddd;
}
#confirmBox .message
{
text-align: left;
margin-bottom: 8px;
}
Or simply:
click me!
This plugin can help you jquery-confirm easy to use
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
confirm: function(){
alert('Confirmed!');
},
cancel: function(){
alert('Canceled!')
}
});
This a full responsive solution using vanilla javascript :
// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");
function show_dialog() {
/* A function to show the dialog window */
overlayme.style.display = "block";
}
// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
/* code executed if confirm is clicked */
overlayme.style.display = "none";
}
// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
/* code executed if cancel is clicked */
overlayme.style.display = "none";
}
.popup {
width: 80%;
padding: 15px;
left: 0;
margin-left: 5%;
border: 1px solid rgb(1,82,73);
border-radius: 10px;
color: rgb(1,82,73);
background: white;
position: absolute;
top: 15%;
box-shadow: 5px 5px 5px #000;
z-index: 10001;
font-weight: 700;
text-align: center;
}
.overlay {
position: fixed;
width: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,.85);
z-index: 10000;
display :none;
}
#media (min-width: 768px) {
.popup {
width: 66.66666666%;
margin-left: 16.666666%;
}
}
#media (min-width: 992px) {
.popup {
width: 80%;
margin-left: 25%;
}
}
#media (min-width: 1200px) {
.popup {
width: 33.33333%;
margin-left: 33.33333%;
}
}
.dialog-btn {
background-color:#44B78B;
color: white;
font-weight: 700;
border: 1px solid #44B78B;
border-radius: 10px;
height: 30px;
width: 30%;
}
.dialog-btn:hover {
background-color:#015249;
cursor: pointer;
}
<div id="content_1" class="content_dialog">
<p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
<p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>
<button id="btn-show-dialog">Ok</button>
<div class="overlay" id="dialog-container">
<div class="popup">
<p>This will be saved. Continue ?</p>
<div class="text-right">
<button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
<button class="dialog-btn btn-primary" id="confirm">Ok</button>
</div>
</div>
</div>
You can intercept the onSubmit event using JavaScript.
Then call a confirmation alert and then grab the result.
Another way to do this:
$("input[name='savedata']").click(function(e){
var r = confirm("Are you sure you want to save now?");
//cancel clicked : stop button default action
if (r === false) {
return false;
}
//action continues, saves in database, no need for more code
});
xdialog provides a simple API xdialog.confirm(). Code snippet is following. More demos can be found here
document.getElementById('test').addEventListener('click', test);
function test() {
xdialog.confirm('Are you sure?', function() {
// do work here if ok/yes selected...
console.info('Done!');
}, {
style: 'width:420px;font-size:0.8rem;',
buttons: {
ok: 'yes text',
cancel: 'no text'
},
oncancel: function() {
console.warn('Cancelled!');
}
});
}
<link href="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/xxjapp/xdialog#3/xdialog.min.js"></script>
<button id="test">test</button>
Made super simple, tiny vanilla js confirm dialog with Yes and No buttons.
It's a pity we can't customize the native one.
https://www.npmjs.com/package/yesno-dialog.
Another solution apart from the others is to use the new dialog element. You need to make use of show or showModal methods based on interactivity with other elements. close method can be used for closing the open dialog box.
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
const dialogEl = document.querySelector("dialog");
const openDialog = document.querySelector("button.open-dialog");
const yesBtn = document.querySelector(".yes");
const noBtn = document.querySelector(".no");
const result = document.querySelector(".result");
openDialog.addEventListener("click", () => {
dialogEl.showModal();
});
yesBtn.addEventListener("click", () => {
// Below line can be replaced by your DB query
result.textContent = "This could have been your DB query";
dialogEl.close();
});
noBtn.addEventListener("click", () => {
result.textContent = "";
dialogEl.close();
});
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
body {
font-family: "Roboto";
}
button {
background: hsl(206deg 64% 51%);
color: white;
padding: 0.5em 1em;
border: 0 none;
cursor: pointer;
}
dialog {
border: 0 none;
}
.result {
margin-top: 1em;
}
<dialog>
<button class="yes">Yes</button>
<button class="no">No</button>
</dialog>
<button class="open-dialog">Click me</button>
<div class="result"></div>
Can I use?
Right now the compatibility is great with all the modern browsers.
I'm currently working on a web workflow which already has it's own notifications/dialog boxes, and I recently (like, today) created a tiny, custom (and tailored to the project needs) YES/NO dialog box.
All dialog boxes appeard over a modal layer. Full user attention is required.
I define the options configurations in this way. This options are used to define the buttons text, and the values associated to each button when there clicked:
optionsConfig = [
{ text: 'Yes', value: true },
{ text: 'No', value: false }
]
The use of the function goes something like this:
const answer = await notifier.showDialog('choose an option', options.config);
if (answer) {
// 'Yes' was clicked
} else {
// 'No' was clicked!
}
What I do, it's simply creating a async event handler for each option, it means, there is a simple handler assigned to each button. Each handler returns the value of the option. The handlers are pushed inside an array.
The array is then passed to Promise.race, and that is the return value of the showDialog method, which will correspond to the value's actual value (the one returned by the handler).
Can't provide too much code. As I said it's a very specific case, but the idea may be usefull for other implementations. Twenty lines of code or so.
A vanilla JavaScript option with a class for creating the custom modal dialog which includes a text box:
jsfiddle:
https://jsfiddle.net/craigdude/uh82mjtb/2/
html:
<!DOCTYPE html>
<html>
<style>
.modal_dialog
{
box-sizing: border-box;
background-color: #ededed;
border-radius: 5px;
border: 0.5px solid #ccc;
font-family: sans-serif;
left: 30%;
margin-left: -50px;
padding: 15px 10px 10px 5px;
position: fixed;
text-align: center;
width: 320px;
}
</style>
<script src="./CustomModalDialog.js"></script>
<script>
var gCustomModalDialog = null;
/** this could be static html from the page in an "invisible" state */
function generateDynamicCustomDialogHtml(){
var html = "";
html += '<div id="custom_modal_dialog" class="modal_dialog">';
html += 'Name: <input id="name" placeholder="Name"></input><br><br>';
html += '<button id="okay_button">OK</button>';
html += '<button id="cancel_button">Cancel</button>';
html += '</div>';
return html;
}
function onModalDialogOkayPressed(event) {
var name = document.getElementById("name");
alert("Name entered: "+name.value);
}
function onModalDialogCancelPressed(event) {
gCustomModalDialog.hide();
}
function setupCustomModalDialog() {
var html = generateDynamicCustomDialogHtml();
gCustomModalDialog = new CustomModalDialog(html, "okay_button", "cancel_button",
"modal_position", onModalDialogOkayPressed, onModalDialogCancelPressed);
}
function showCustomModalDialog() {
if (! gCustomModalDialog) {
setupCustomModalDialog();
}
gCustomModalDialog.show();
gCustomModalDialog.setFocus("name");
}
</script>
<body>
<button onclick="showCustomModalDialog(this)">Show Dialog</button><br>
Some content
<div id="modal_position">
</div>
Some additional content
</body>
</html>
CustomModalDialog.js:
/** Encapsulates a custom modal dialog in pure JS
*/
class CustomModalDialog {
/**
* Constructs the modal content
* #param htmlContent - content of the HTML dialog to show
* #param okayControlElementId - elementId of the okay button, image or control
* #param cancelControlElementId - elementId of the cancel button, image or control
* #param insertionElementId - elementId of the <div> or whatever tag to
* insert the html at within the document
* #param callbackOnOkay - method to invoke when the okay button or control is clicked.
* #param callbackOnCancel - method to invoke when the cancel button or control is clicked.
* #param callbackTag (optional) - to allow object to be passed to the callbackOnOkay
* or callbackOnCancel methods when they're invoked.
*/
constructor(htmlContent, okayControlElementId, cancelControlElementId, insertionElementId,
callbackOnOkay, callbackOnCancel, callbackTag) {
this.htmlContent = htmlContent;
this.okayControlElementId = okayControlElementId;
this.cancelControlElementId = cancelControlElementId;
this.insertionElementId = insertionElementId;
this.callbackOnOkay = callbackOnOkay;
this.callbackOnCancel = callbackOnCancel;
this.callbackTag = callbackTag;
}
/** shows the custom modal dialog */
show() {
// must insert the HTML into the page before searching for ok/cancel buttons
var insertPoint = document.getElementById(this.insertionElementId);
insertPoint.innerHTML = this.htmlContent;
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
okayControl.addEventListener('click', event => {
this.callbackOnOkay(event, insertPoint, this.callbackTag);
});
cancelControl.addEventListener('click', event => {
this.callbackOnCancel(event, insertPoint, this.callbackTag);
});
} // end: method
/** hide the custom modal dialog */
hide() {
var insertPoint = document.getElementById(this.insertionElementId);
var okayControl = document.getElementById(this.okayControlElementId);
var cancelControl = document.getElementById(this.cancelControlElementId);
insertPoint.innerHTML = "";
okayControl.removeEventListener('click',
this.callbackOnOkay,
false
);
cancelControl.removeEventListener('click',
this.callbackOnCancel,
false
);
} // end: method
/** sets the focus to given element id
*/
setFocus(elementId) {
var focusElement = document.getElementById(elementId);
focusElement.focus();
if (typeof focusElementstr === "HTMLInputElement")
focusElement.select();
}
} // end: class
The easiest way to ask before action on click is following
<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>
document.getElementById("button").addEventListener("click", function(e) {
var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");
if (cevap) {
location.href='Http://www.evdenevenakliyat.net.tr';
}
});

Categories