I want to get a confirm message on clicking delete (this maybe a button or an image). If the user selects 'Ok' then delete is done, else if 'Cancel' is clicked nothing happens.
I tried echoing this when the button was clicked, but echoing stuff makes my input boxes and text boxes lose their styles and design.
Write this in onclick event of the button:
var result = confirm("Want to delete?");
if (result) {
//Logic to delete the item
}
You can better use as follows
Delete
This is how you would do it with unobtrusive JavaScript and the confirm message being hold in the HTML.
Delete
This is pure vanilla JS, compatible with IE 9+:
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice) {
window.location.href = this.getAttribute('href');
}
});
}
See it in action: http://codepen.io/anon/pen/NqdKZq
function ConfirmDelete()
{
return confirm("Are you sure you want to delete?");
}
<input type="button" onclick="ConfirmDelete()">
it is very simple and one line of code
Delete
Try this. It works for me
Remove
improving on user1697128 (because I cant yet comment on it)
<script>
function ConfirmDelete()
{
return confirm("Are you sure you want to delete?");
}
</script>
<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>
will cancel form submission if cancel is pressed
I would like to offer the way I do this:
<form action="/route" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="the_token">
<button type="submit" class="btn btn-link" onclick="if (!confirm('Are you sure?')) { return false }"><span>Delete</span></button>
</form>
It can be simplify to this:
<button onclick="return confirm('Are you sure you want to delete?');" />
HTML
<input onclick="return myConfirm();" type="submit" name="deleteYear" class="btn btn-danger" value="Delete">
Javascript
<script>
function myConfirm() {
var result = confirm("Want to delete?");
if (result==true) {
return true;
} else {
return false;
}
}
If you are interested in some quick pretty solution with css format done, you can use SweetAlert
$(function(){
$(".delete").click(function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}).then(isConfirmed => {
if(isConfirmed) {
$(".file").addClass("isDeleted");
swal("Deleted!", "Your imaginary file has been deleted.", "success");
}
});
});
});
html { zoom: 0.7 } /* little "hack" to make example visible in stackoverflow snippet preview */
body > p { font-size: 32px }
.delete { cursor: pointer; color: #00A }
.isDeleted { text-decoration:line-through }
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<link rel="stylesheet" href="http://t4t5.github.io/sweetalert/dist/sweetalert.css">
<p class="file">File 1 <span class="delete">(delete)</span></p>
HTML:
Delete
Using jQuery:
$('.delete').on("click", function (e) {
e.preventDefault();
var choice = confirm($(this).attr('data-confirm'));
if (choice) {
window.location.href = $(this).attr('href');
}
});
<form onsubmit="return confirm('Are you sure?');" />
works well for forms. Form-specific question: JavaScript Form Submit - Confirm or Cancel Submission Dialog Box
Delete Product
<!-- language: lang-js -->
<script>
function del_product(id){
$('.process').css('display','block');
$('.process').html('<img src="./images/loading.gif">');
$.ajax({
'url':'./process.php?action=del_product&id='+id,
'type':"post",
success: function(result){
info=JSON.parse(result);
if(result.status==1){
setTimeout(function(){
$('.process').hide();
$('.tr_'+id).hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
} else if(result.status==0){
setTimeout(function(){
$('.process').hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}
}
});
}
</script>
Practice
<form name=myform>
<input type=button value="Try it now"
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>
Web Original:
http://www.javascripter.net/faq/confirm.htm
to set a conformation message when you delete something in php & mysql...
use this script code:
<script>
function Conform_Delete()
{
return conform("Are You Sure Want to Delete?");
}
</script>
use this html code:
<a onclick="return Conform_Delete()" href="#">delete</a>
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
function confirmDelete()
{
var r=confirm("Are you sure you want to delte this image");
if (r==true)
{
//User Pressed okay. Delete
}
else
{
//user pressed cancel. Do nothing
}
}
<img src="deleteicon.png" onclick="confirmDelete()">
You might want to pass some data with confirmDelete to determine which entry is to be deleted
Using jQuery:
$(".delete-link").on("click", null, function(){
return confirm("Are you sure?");
});
I know this is old, but I needed an answer and non of these but alpesh's answer worked for me and wanted to share with people that might had the same problem.
<script>
function confirmDelete(url) {
if (confirm("Are you sure you want to delete this?")) {
window.open(url);
} else {
false;
}
}
</script>
Normal version:
<input type="button" name="delete" value="Delete" onClick="confirmDelete('delete.php?id=123&title=Hello')">
My PHP version:
$deleteUrl = "delete.php?id=" .$id. "&title=" .$title;
echo "<input type=\"button\" name=\"delete\" value=\"Delete\" onClick=\"confirmDelete('" .$deleteUrl. "')\"/>";
This might not be the correct way of doing it publicly but this worked for me on a private site. :)
Its very simple
function archiveRemove(any) {
var click = $(any);
var id = click.attr("id");
swal.fire({
title: 'Are you sure !',
text: "?????",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'yes!',
cancelButtonText: 'no'
}).then(function (success) {
if (success) {
$('a[id="' + id + '"]').parents(".archiveItem").submit();
}
})
}
function del_confirm(msg,url)
{
if(confirm(msg))
{
window.location.href=url
}
else
{
false;
}
}
<a onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>
<SCRIPT LANGUAGE="javascript">
function Del()
{
var r=confirm("Are you sure?")
if(r==true){return href;}else{return false;}
}
</SCRIPT>
your link for it:
<a href='edit_post.php?id=$myrow[id]'> Delete</a>
The onclick handler should return false after the function call. For eg.
onclick="ConfirmDelete(); return false;">
I think the simplest unobtrusive solution would be:
Link:
Delete
Javascript:
$('.delete').click(function () {
return confirm("Are you sure?");
});
Delete Product
function del_product(id){
$('.process').css('display','block');
$('.process').html('<img src="./images/loading.gif">');
$.ajax({
'url':'./process.php?action=del_product&id='+id,
'type':"post",
success: function(result){
info=JSON.parse(result);
if(result.status==1){
setTimeout(function(){
$('.process').hide();
$('.tr_'+id).hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}else if(result.status==0){
setTimeout(function(){
$('.process').hide();
},3000);
setTimeout(function(){
$('.process').html(result.notice);
},1000);
}
}
});
}
Here is another simple example in pure JS using className and binding event to it.
var eraseable = document.getElementsByClassName("eraseable");
for (var i = 0; i < eraseable.length; i++) {
eraseable[i].addEventListener('click', delFunction, false); //bind delFunction on click to eraseables
}
function delFunction(){
var msg = confirm("Are you sure?");
if (msg == true) {
this.remove(); //remove the clicked element if confirmed
}
};
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>
<script>
function deleteItem()
{
var resp = confirm("Do you want to delete this item???");
if (resp == true) {
//do something
}
else {
//do something
}
}
</script>
call this function using onClick
For "confirmation message on delete" use:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Searching.aspx/Delete_Student_Data",
data: "{'StudentID': '" + studentID + "'}",
dataType: "json",
success: function (data) {
alert("Delete StudentID Successfully");
return true;
}
Angularjs With Javascript Delete Example
html code
<button ng-click="ConfirmDelete(single_play.play_id)" type="submit" name="actiondelete" value="1"><img src="images/remove.png" alt="Delete"></button>
"single_play.play_id" is any angularjs variable suppose you want to pass any parameter during the delete action
Angularjs code inside the app module
$scope.ConfirmDelete = function(yy)
{
var x = confirm("Are you sure you want to delete?");
if (x) {
// Action for press ok
$http({
method : 'POST',
url : 'sample.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ delete_play_id : yy})
}).then(function (response) {
$scope.message = response.data;
});
}
else {
//Action for cancel
return false;
}
}
Related
I am trying to submit a form with a little error handling. when the fields are empty there will be a warning and it shouldn't be saved on DB. if the fields are filled there should be a success alert. My case is still the empty value is being saved.
HTML
<input type="submit" id="add" onclick="emptyHandling();" name="_add" class="btn btn-primary btn-size" value="Add"/>
//FORM SUBMIT
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>'); // REPONSE MESSAGE
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling(){
var inv = $("#inv").val();
if(inv == ''){
var message = "Field Left Empty";
alertMessage(message);
}else{
successMessage();
}
return false; // THIS IS BEING RETURNED FALSE
}
//WARNING ALERT
function alertMessage(titleMessage){
swal({
title: titleMessage,
text: "Mandatory Fields are Required to be Filled",
type: "warning",
confirmButtonClass: "btn btn-danger"
});
}
The return is made false on error handling which should stop the next processes. I am not really sure of where the mistake is made.
You can remove onclick from your submit button and move that function call inside your form submit handler . Then , inside this check if the validation function return true/false depending on this execute your ajax call.
Demo Code :
$(document).ready(function() {
$("#form").on('submit', function(e) {
e.preventDefault();
//call function..
if (emptyHandling()) {
//your ajax...
console.log("inside ajax....")
}
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling() {
var flag = true
var inv = $("#inv").val();
if (inv == '') {
var message = "Field Left Empty";
alertMessage(message);
flag = false
} else {
successMessage();
}
return flag; // return flag//
}
//WARNING ALERT
function alertMessage(titleMessage) {
//swal...
console.log(titleMessage)
}
function successMessage() {
console.log("All good...")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="form">
<input type="text" id="inv">
<input type="submit" id="add" name="_add" class="btn btn-primary btn-size" value="Add" />
</form>
Currently, I have this jQuery code for my cancel button
$('#cancel').click(function () {
$('#edit').show();
$('#savechanges, #cancel').hide();
$("#target :input").prop("disabled", true);
});
How can I make an alert pop up if I click the cancel button? I know this is simple but I just want to learn.
You can use the confirm alert to make sure the user confirms their action before proceeding with the code you want for the cancel event.
$('#cancel').click(function() {
if (confirm('Are you sure?')) {
$('#edit').show();
$('#savechanges, #cancel').hide();
$("#target :input").prop("disabled", true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="cancel">cancel</button>
<button id="savechanges">Save</button>
<div id="edit">edit</div>
You can use confirm API:
if(confirm("Are you sure?"))
{
//Ok button pressed...
}
else
{
//Cancel button pressed...
}
Docs here: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
"OK" and "Cancel" button can't be change text to Yes/No or anything else that works cross-browser. If you want that, you can find a jquery plugin for custom create a dialog for your own.
Here are some examples for different types of prompts
$(function() {
$("[data-confirm]").on("click", function(){
return confirm($(this).data("confirm"));
});
$("[data-alert]").on("click", function(){
return alert($(this).data("alert"));
});
$("[data-prompt]").on("click", function(){
return prompt($(this).data("prompt"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-confirm="Confirm!">Window.confirm()</button>
<button data-alert="Alert!">Window.alert()</button>
<button data-prompt="Prompt!">Window.prompt()</button>
The easiest way could be the simple window.confirm('...') solution.
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
use alert('Are you sure you want to delete') for this. Or maybe you want to use confirm('press ok to confirm').
<script>
function myFunction() {
var txt;
var r = confirm("Press a button!");
//alert("Hello\nHow are you?");
if (r == true) {
txt = "You pressed OK!";
//write you own functionality here.
} else {
txt = "You pressed Cancel!";
}
}
</script>
You can use sweet alert that isnt look like stone age style
$('button').click(function(){
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9.7.1/dist/sweetalert2.all.min.js" integrity="sha256-1pZ3aajcQuFEOG/veUw/WxQjAMJiCSTZo8wH+opDplY=" crossorigin="anonymous"></script>
<button>Popup</button>
Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php
Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}
I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.
'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});
i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});
<script LANGUAGE="JavaScript">
function confirmSubmit() {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if(r) {
return true;
} else {
return false;
}
});
}
</script>
<form name='cancel_form'id='cancel_form' method='POST' action="">
<center>
<input type='submit' name='confirm_appointment' value='Cancel Appointment' onclick='return confirmSubmit();'>
</center>
</form>
<script type='text/javascript'>
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var saveUrl = "<?php echo $this->url(array('controller' => 'appointment', 'action' =>'cancelsave'));?>";
$('#cancel_form').ajaxForm({ success: saveCallbk , url : saveUrl });
function saveCallbk(responseText) {
jAlert(responseText,'Alert Dialog');
if(responseText.indexOf("ERROR")<0) {
$(location).attr('href',redirectUrl);
}
}
</script>
When I submit the form I call this function and use jConfirm from jQuery. I print r. It's printing properly (e.g. true and false), but return false or return true has no effect -- it just shows the pop up and submits the form, and does not wait for confirmation. How to solve this?
The ajaxForm plugin takes care of the submission by itself and it needs a submit button. If I use:
function confirmSubmit() {
var agree=confirm("Is the Appointment Cancelled?");
if (agree) {
return true;
} else {
return false;
}
}
like default javascript it works well
Use type="button" instead of type="submit" and attach this on the click event of your form button.
$('#button').click(function () {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if (r) {
$('#form').submit();
}
});
});
What Ivo said.
Your function confirmSubmit should return true or false.
Edit -
I am not familiar with jConfirm, but you may need to return the results from jConfirm, like this.
<script>
function confirmSubmit()
{
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog',
function(r) {
if(r){return true;} else {return false;}
});
}
</script>
if this is the case, you could do away with confirmSubmit() altogether and just say:
$('#form').submit(function() {
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) { return r; } );
});
Hope this helps...
Dang that Ivo is GOOD :-) Personally, i do what Ivo has demonstrated. Create an input of type="button", then delegate a click function.
This is how I cancel submit events using JavaScript and jQuery:
First I have a utility function called cancelEvent: (Which I picked up from this blog entry.)
function cancelEvent(e)
{
e = e ? e : window.event;
if(e.stopPropagation)
e.stopPropagation();
if(e.preventDefault)
e.preventDefault();
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
return false;
}
Then I'll have the main JavaScript file that will contain code something like this:
function validateForm(e)
{
var validated = true;
/*
Validation code goes here.
If validation fails set validated to false
*/
//If validation fails then at the end I'll want to cancel the submit event
if(validated)
{
return true;
}
return cancelEvent(e);
}
jQuery(document).ready(function()
{
jQuery("#theForm").submit(validateForm);
}