I'm trying to create customizable checkboxes using buttons. I'm able to differentiate which button class has been selected, but I've been unable to track the button class post form submission. Ideally, instead of reseting the buttons to a default value when the page is loaded or submitted, I can keep whatever input was initially provided. I've tried using the isset() php function, but I don't think it's a valid solution in this circumstance. Are there any alternatives? Find my code below:
<form id="my-form" method="post">
<html>
<body >
<style>
.button {
color: white;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 12px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {
border-radius: 100%;
background-color: green;
border: none;
}
.button2 {
border-radius: 100%;
background-color: red;
border: none;
}
</style>
<div id="test1"></div>
<div id="test2"></div>
<!-- invalid code?
<?php
echo isset($_POST["t1test"]);
echo isset($_POST["t2test"]);
echo $_POST["t1test"];
echo $_POST["t2test"];
?>
-->
<script type="text/javascript">
function makeButton(div, val) {
var element = document.getElementById(val);
var button = document.createElement("button");
var span = document.createElement("span");
// change to account for submitted settings
if (element == null) {
button.setAttribute("class", "button button1"); }
else {
var cL1 = element.classList.contains("button1");
var cL2 = element.classList.contains("button2");
element.parentNode.removeChild(element);
if (cL2 == true) { button.setAttribute("class", "button button1"); }
if (cL1 == true) { button.setAttribute("class", "button button2"); }
}
button.setAttribute("type", "button");
button.setAttribute("id", val);
button.setAttribute("name", val);
var testDiv = document.getElementById(div);
testDiv.appendChild(button);
button.addEventListener ("click", function() { makeButton(div, val); })
}
window.onload = function() {
makeButton("test1", "t1test");
makeButton("test2", "t2test"); }
</script>
</body>
</html>
<button id="submit">Submit</button>
</form>
How about removing the form tags and adding a "click" event listener to the submit button? The code shown below inserted appended to the end of the file:
<script>
document.getElementById("submit").addEventListener("click", function(){
var elements = ["t1test", "t2test"];
for(var i = 0; i < elements.length; i++) {
var element = document.getElementById(elements[i]);
console.log(element.classList.contains("button1"));
console.log(element.classList.contains("button2"));
}
});
</script>
This way the page will not be reloaded when the button is pressed thus retaining button selection.
Related
I'm making a note taker app that gives you the option to view said note in a modal whenever the button is clicked. There are two ways the close it by clicking the "X" button or by clicking outside of the modal.
When I proceed with one of these options, the modal will close successfully, but if I open it a second time neither the "X" button or clicking outside seem to work. How could I fix this problem?
class Input {
constructor(note) {
this.note = note;
}
}
class UI {
addNote(input) {
// Get table body below form
const content = document.querySelector(".content");
// Create tr element
const row = document.createElement("tr");
// Insert new HTML into div
row.innerHTML = `
<td>
${input.note}
<br><br>
<button class="modalBtn">View Note</button>
</td>
`;
content.appendChild(row);
// Event listener to make modal
document.querySelector(".modalBtn").addEventListener("click", function(e) {
// Get container div
const container = document.querySelector(".container");
// Create div
const div = document.createElement("div");
// Assign class to it
div.className = "modal";
// Insert HTML into div
div.innerHTML = `
<div class="modal-content">
<span class="closeBtn">×</span>
<div>
<p>${input.note}</p>
</div>
</div>
`;
// Append the new div to the container div
container.appendChild(div);
// Get modal
const modal = document.querySelector(".modal");
// Event listener to close modal when "x" is clicked
document.querySelector(".closeBtn").addEventListener("click", function() {
modal.style.display = "none";
});
// Event listener to close when the window outside the modal is clicked
window.addEventListener("click", function(e) {
if (e.target === modal) {
modal.style.display = "none";
}
});
});
}
// Clear input field
clearInput() {
note.value = "";
}
}
// Event listener for addNote
document.getElementById("note-form").addEventListener("submit", function(e) {
// Get form value
const note = document.getElementById("note").value;
// Instantiate note
const input = new Input(note);
// Instantiate UI
const ui = new UI();
// Validate form (make sure input is filled)
if (note === "") {
// Error alert
alert("Please fill in text field!");
}
else {
// Add note
ui.addNote(input);
// Clear input field
ui.clearInput();
}
e.preventDefault();
});
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 17px;
line-height: 1.6;
}
.button {
background: coral;
padding: 1em 2em;
color: #fff;
border: 0;
}
.button:hover {
background: #333;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #f4f4f4;
margin: 20% auto;
padding: 20px;
width: 70%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-direction: 1s;
}
.closeBtn {
color: #ccc;
float: right;
font-size: 30px;
}
.closeBtn:hover,
.closeBtnBtn:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" integrity="sha512-5fsy+3xG8N/1PV5MIJz9ZsWpkltijBI48gBzQ/Z2eVATePGHOkMIn+xTDHIfTZFVb9GMpflF2wOWItqxAP2oLQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
<title>Note Taker</title>
</head>
<body>
<div class="container">
<h1>Note Taker</h1>
<h5>Add A New Note:</h5>
<form id="note-form">
<div>
<label>Note:</label>
<textarea name="Note" id="note" class="u-full-width"> </textarea>
</div>
<div>
<button type="submit" class="button-primary">Add Note</button>
</div>
</form>
<table>
<tbody class="content"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
That happens because when you apply
modal.style.display = "none";
to the modal, you aren't destroying it, you're only hiding it. Additionally, every time you create a modal, and use
const modal = document.querySelector(".modal");
you aren't receiving the new modal you appended to the container, you're receiving the one that it's hidden. That's why the click event doesn't work, because it's being added to the hidden modal. To fix that change,
this:
modal.style.display = "none";
to this:
container.removeChild(modal);
in both EventListeners
In my HTML i have put a script and a div. Now i want to make 3 buttons next to each other in the while block in the middle of the page. I want to make the 3 buttons without changing the html and thus make it dynamic inside the javascript.
So far i have put a var in the javascript but i do not know what to do now..
I earlier made a html page with a button element inside it and then change all of it using the html but i cant figure out how to do this if there isn't a button element inside the html page.
HTML:
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
CSS:
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
JS:
var buttons = document.getElementsById("container");
button.onclick = onbuttonclicked;
function onbuttonclicked(){
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled=true;
} else {
button1.style.backgroundColor = "green";
button1.disabled=false;
}
}
so like here each button has its own text and color
Create the buttons and append them as children of your buttons container. Here I am creating one button. You can do the same for other buttons:
var buttons = document.getElementById("container");
var button1 = document.createElement("button");
button1.onclick = onbuttonclicked;
buttons.appendChild(button1);
function onbuttonclicked() {
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled = true;
} else {
button1.style.backgroundColor = "green";
button1.disabled = false;
}
}
Note that onbuttonclicked will always evaluate to true because you are checking whether the function is defined or not. Also, if you want to change the background and disabled attribute of the clicked button, rather than button1 explicitly, you should use this instead of button1.
var container = document.querySelector("#container");
var arr = ['success','danger','warning'];
for (var i = 0; i < 3; i++) {
var button = document.createElement("button");
button.setAttribute("attribute", arr[i]);
button.innerHTML = arr[i];
button.className += arr[i];
container.appendChild(button);
console.log(button)
}
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
btn {
border: none;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
}
.success {
color: black;
background:green;
}
.success:hover {
background-color: #4CAF50;
color: white;
}
.warning {
background: yellow;
color:black;
}
.warning:hover {
background: #ff9800;
color: white;
}
.danger {
background: red;
color:black;
}
.danger:hover {
background: #f44336;
color: white;
}
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
I think like this?
So for this you are trying to manipulate the DOM using JavaScript, take your div#container and you are trying to append three button elements. The process for doing this (or really any HTML Element with JS DOM manipulation is fairly similar, you create the element, add the attributes you want, and then "append" it to the main element where you want it inserted)
Check out my example below to add 3 buttons to your <div id="container">:
var container = document.querySelector("#container"); //or use document.getElementById("container"), makes no difference
for (var i = 0; i < 3; i++) {
var button = document.createElement("button"); //works with any HTML5 element
button.setAttribute("attribute", "value"); //Use this to add attributes such as id, class, styles, or even event listeners like onclick
button.innerHTML = "Button Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button);
}
Since you said you want the buttons next to each other (I'm assuming this means side-by-side) then you can add a style to your CSS
button {
display: inline;
}
but of course that would depend on your usage, meaning if you wanted all buttons to be inline. If you wanted just those three then you can use the .setAttribute("class", "classname"); to add a class and then define that class to have the same style.
You can also make your container a CSS flexbox and have each of the buttons aligned horizontally
#container {
display: flexbox;
flex-direction: row; /*Use row for horizontal, column for vertical*/
}
and you wouldn't need to style your buttons. But the choice is yours.
Edit: to make 2 buttons, one green and one red,
//Make a green text button1
var button1 = document.createElement("button"); //works with any HTML5 element
button1.style.color = "green";
button1.innerHTML = "Button1 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button1);
//Make a red text button2
var button2 = document.createElement("button"); //works with any HTML5 element
button2.style.color = "red";
button2.innerHTML = "Button2 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button2);
If you wanted to change the background colors as well you could add button.style.backgroundColor = "pink" or whatever color you'd like
Check out: JavaScript DOM Methods, this was a REAL help to me when I was learning what you're trying to do right now!
To give the buttons a function use the onclick value of the button, so in the above script we can add something like this:
button1.onclick = button1AfterClicked;
//Or
button1.setAttribute("onclick", "button1AfterClicked");
And since JavaScript is pretty lenient we can define our button1AfterClicked() anywhere
function button1AfterClicked() {
button1.style.color = "some color";
//And so forth...
}
For these kinds of questions I highly suggest looking up the answer on google because I know W3Schools does a splendid job on explaining the basics and more: OnClick Event JavaScript
You Can do it with jquery check is this right ?
$("#container").html('<button class="green-button">Button1</button><button class="red-button">Button2</button><button class="yellow-button">Button3</button>');
$( ".red-button" ).click(function() {
$(".red-button").css("background-color", "red");
});
$( ".green-button" ).click(function() {
$(".green-button").css("background-color", "green");
});
$( ".yellow-button" ).click(function() {
$(".yellow-button").css("background-color", "yellow");
});
<div id="container"></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Following is what might help you,you can set margin and padding to your needs:
var button = document.createElement("button");
button.innerHTML = "Do Something";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert("did something");
});
The code provided is all you needed for your current project
You can add the style of the button in CSS
// container of buttons
const containerBtn = document.querySelector('.container');
let createBtns = (classParam, text) => {
let btn = document.createElement('button');
btn.classList.add(classParam);
btn.innerText = text;
containerBtn.append(btn);
return btn;
};
// 1. add the button **class**
// 2. add the button text
let btn1 = createBtns('btn-1', 'test');
// add event listener to btn1
btn1.addEventListener('click', () => {
console.log(1);
});
This is an example where three buttons are created and styled with CSS. They use the nth-of-type() and attribute selectors to style the buttons based on their position and disabled state.
Do note that when disabling the buttons they won't listen to the click event anymore.
const container = document.getElementById('container');
for (let i = 0; i < 3; i++) {
const button = document.createElement('button');
button.textContent = `Button ${i + 1}`;
container.append(button);
}
container.addEventListener('click', event => {
const { target } = event;
if (!target.tagName.toLowerCase() === 'button') {
return;
}
if (!target.disabled) {
target.disabled = true;
} else {
target.disabled = false;
}
});
#container {
display: flex;
}
#container button {
padding: 15px;
color: white;
}
#container button:first-of-type {
background-color: red;
}
#container button:nth-of-type(2) {
background-color: blue;
}
#container button:last-of-type {
background-color: goldenrod;
}
#container button[disabled] {
background-color: black;
}
<div id="container"></div>
I have an input box which you can enter items, submit it, and create a box with it's own delete button to remove it. Problem is, after deleting a number of boxes, and then entering something new in input, all the previous items that were deleted get reloaded, including the new item.
How can I prevent reloading of already removed boxes?
Fiddle (Stacksnippets do not allow submit)
This is my Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Shopping List Example</title>
<link rel="stylesheet" type="text/css" href="css-list.css">
</head>
<div id="centerPanel">
<form class="my-list-form">
<input type="text" class="input" name="add-input" id="add-input">
<button class="add-button" id="submitBtn">Add</button>
</form>
<ul class="my-list-ul"></ul>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script src="js-list.js"></script>
</html>
JS:
var state = {items:[]};
var addItem = function(state, item)
{
state.items.push(item);
}
var displayItem = function(state, element){
var htmlItems = state.items.map(function(item){
return '<li class="box">' + item + '</br><button class="divBtns" id="deleteBtn">Delete</button>' + '</li>';
});
element.html(htmlItems);
}
//After deleting items, this button again loads all items that have been created since
//the page loaded up, including the new item.
//Needs to be fixed to not reload the deleted items
$('.my-list-form').submit(function(event){
event.preventDefault();
addItem(state, $('.input').val());
displayItem(state, $('.my-list-ul') );
/* alert(state.items[1]); shows that the items array holds everything that is turned into a div*/
})
$(document).ready(function(e){
$('ul').on('click', '#deleteBtn', function(event){
var rmvButton = $(this).closest('li');
rmvButton.remove();
});
})
css:
* {
font-family: sans-serif;
font-weight: normal;
}
#centerPanel {
margin-left: 50px;
margin-top: 50px;
padding-left: 10px;
}
h1 {
font-size: 34px;
}
.font-size {
font-size: 17px;
}
#add-input {
height:25px;
width: 190px;
font-size: 16px;
}
button {
font-size: 17px;
}
#submitBtn {
height: 30px;
width: 85px;
}
.divBtns {
margin-top: 10px;
}
.box {
border: 1px solid black;
border-color: grey;
width: 153px;
height: 65px;
padding: 20px;
font-style: italic;
font-size: 22px;
margin-bottom:10px;
margin-right: 10px;
}
ul {
list-style-type: none;
margin-left:-40px;
color: grey;
}
li {
float: left;
}
It appears you never remove anything from the state object, which is added to every time you run addItem().
You'd need a way to remove a specific item from this array, probably by getting the index of the li to delete and doing
state.items.splice(index, 1);
Store the index as a data attribute on the button:
var displayItem = function(state, element){
var i = 0;
var htmlItems = state.items.map(function(item){
return '<li class="box">' + item + '</br><button class="divBtns" ' +
'id="deleteBtn" data-index="' + (i++) + '">Delete</button>' + '</li>';
});
element.html(htmlItems);
}
Then you can get it in the click callback
var index = $(this).data('index');
You can update state to solve this problem.
It's my code:
...
var deleteItem = function(state, itemId) {
var index = 0;
var isFind = state.items.some(function(item, i) {
if (item.id == itemId) {
index = i;
return true;
} else {
return false;
}
});
if (isFind) {
state.items.splice(index, 1);
}
}
...
$(document).ready(function(e){
$('ul').on('click', '#deleteBtn', function(event){
...
// update state
deleteItem(state, $(this).parent().data('id'));
});
})
https://jsfiddle.net/q483cLp9/
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.
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';
}
});