How to pass parameters to the jquery alert function - javascript

I have html table with a delete button. I want to delete the row on button click. For this purpose, when I click a button with class '.btn-danger' which will open a JQuery alert window. My problem is how to pass the $(this) of button click to the $.alert Yes function, so I can remove that row. I have my code below.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
$(document).ready(function() {
$('.btn-danger').on('click', function(e){
e.preventDefault();
var me = $(this);
var id = $(this).closest('tr').attr('id');
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function (me) {
//pass value
},
No: function () {
//close function
}
}
});
});
});

Remove me from Yes: function (me) {} because you have already declared it. Then you can call it like below.
Yes: function() {
console.log(me)
},
$('.btn-danger').on('click', function(e) {
e.preventDefault();
var me = $(this);
var id = $(this).closest('tr').attr('id');
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function() {
console.log(me)
//$("tr#" + id).remove() <--- example of removing the row
},
No: function() {
//close function
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css" rel="stylesheet" />
<button class="btn btn-danger">delete</button>

You can try something like this code (If I correct understand you issue)
$(document).ready(function() {
$('.btn-danger').on('click', function(e){
e.preventDefault();
var me = $(this);
$.alert({
title: 'Alert!',
content: 'Are you sure you want to delete data?',
buttons: {
Yes: function () {
me.closest('tr').remove();
},
No: function () {
//close function
}
}
});
});
});
jsfiddle example

Related

Custom Javascript confirm window on click button

Hello i am trying to do custom popup for confirm window ( as i know its impossible to change that)
$('.delete_current_form').on('click', function() {
if( confirm("{{ 'Post will be deleted! Continue?'|trans }}") ){
var scheduleEntryId = $(this).attr('data-id');
if (scheduleEntryId) {
$.get('{{ path('schedule_delete_entry', {'id': '0'}) }}'.replace('0', scheduleEntryId));
$(this).attr('data-id', '');
}
$(this).parent().parent().parent().removeClass('selected_field');
$(this).closest('.all_wrap').find('form select, form textarea').val('').change();
$(this).closest('tr').removeClass('green_background');
$(this).closest('.all_wrap').addClass('showing_real');
allCounts();
}
});
As you noticed there is function that is made on click on specific div element. i want to make popup else where to run code only when i click yes, and do nothing when i click no.
<div class="popup">
<div class="yes_button">YES</div>
<div class="no_button">NO</div>
</div>
what i am trying to achieve it
1. i click on delete_current_form button
2. .popup shows up and if i click .yes_button the code that is inside .delete_current_form if runs
confirm() is javascript native method, you can't change its behavior, you can still handle Ok and Cancel click event.
See this fiddle for working of the same:
$(document).ready(function() {
$('.delete_current_form').on('click', function() {
if(confirm("{{ 'Post will be deleted! Continue?'|trans }}") ){
alert("Ok clicked");
// Do whatever you want to do when OK clicked
}
else{
alert("Cancel clicked");
// Do whatever you want to do when Cancel clicked
}
});
});
Comment Edit:
As you can't change the confirm behavior, you can go for a custom modal popup. As the question is tagged with jQuery I would suggest you use jquery-ui.
//Set up the dialog box
$("#myDialog").dialog({
autoOpen : false,
modal : true,
title : "Title",
buttons : {
'Yes' : function() {
var textValue = $('#myTextBox').val();
alert('Yes clicked');
//Do whatever you want to do when Yes clicked
},
'No' : function() {
alert('No clicked');
//Do whatever you want to do when No clicked
$(this).dialog('close');
}
}
});
//Open the dialog box when the button is clicked.
$('#clickMe').click(function() {
$("#myDialog").dialog("open");
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>
<div id="myDialog">
Content of the modal dialog box.
</div>
<button id="clickMe">Click Me</button>
Try the #Thulasiram's answer for creating Yes or No confirm box
Yes or No confirm box using jQuery
Hope this will solve your problem.
ConfirmDialog('Are you sure');
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
// $(obj).removeAttr('onclick');
// $(obj).parents('.Parent').remove();
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Retrieve input value from Jquery UI dialog box

I am working on a small project (just a practice example - not for real use). Its a very simple CRUD application, and I am not aloud to alter the index.html. Also have to use JQuery UI Dialog and not prompt().
I got up to ADD functionality and I'm stuck. I've created a Jquery UI dialog that appends a form - its triggered when 'Add item' is clicked. Then The action for clicking 'yes' in the form needs to return what was in the input. I am unable to retrieve the value and there is no server side technology(like php)involved. function add_item() in answers.js is where I am working now.
I also don't know why, but an additional input box appears on the bottom of my html page after clicking 'Add item' (it should only append to the form )
*Note: CRUD functions begin after document.ready...lower on the page.
Also, besides the one default item in index.html list items are originally from a json file
*
answer.js
$(document).ready(function()
{
///////// REMOVE ALL ////////////
$(document).on("click", "div a:nth-of-type(3)", function(e)
{
e.preventDefault();
remove_all();
});
$("div a:nth-of-type(3)").click(remove_all);
///////// ADD ITEM ////////////
$(document).on("click", "#add_item", function(e)
{
e.preventDefault();
add_item();
});
$("#add_item").click(add_item);
///////// LOAD ALL ////////////
$(document).on("click", "div a:nth-of-type(2)", function(e)
{
e.preventDefault();
load_all();
});
///////// REMOVE ITEM ////////////
$(document).on("click", "#my_list a", function(e)
{
e.preventDefault();
var current_item = $(this).parent();
remove_item(current_item);
});
$("#my_list a").click(remove_item(current_item));
///////// EDITABLE ITEM ////////////
});
/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item()
{
$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');
// JQUERY UI DIALOG
$( "#dialog-form" ).dialog({
resizable: false,
title:'Add new item',
height:240,
width:260,
modal: true,
buttons: {
"Yes": function() {
var test = $('#new_item').val();
alert(test);
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
function remove_all()
{
$('#my_list li').hide();
}
function load_all()
{
$.getJSON( "myLists/myList.json", function( json )
{
var items = json;
$('#my_list li').remove();
$.each(items, function(index,the_item)
{
$('#my_list').append('<li>'+the_item+'x</li>')
});
});
}
function remove_item(current_item)
{
// APPEND DIALOG BOX DIV
$('<div id="dialog-confirm">').appendTo('body');
// JQUERY UI DIALOG
$( "#dialog-confirm" ).dialog({
resizable: false,
title:'Remove this item?',
height:140,
width:260,
modal: true,
buttons: {
"Yes": function() {
$(current_item).hide();
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
INDEX.HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link href="jquery-ui/css/ui-lightness/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="answer.js"></script>
<title>jQuery Test</title>
</head>
<body>
<div>
<h1>My Shopping List</h1>
Add Item | Load List | Clear List
<ul id="my_list">
<li>Brand New Shoes x</li>
</ul>
</div>
</body>
</html>
Offering a few updates that I think might help:
Working Example: https://jsfiddle.net/Twisty/5g72nncw/
$(document).ready(function() {
///////// REMOVE ALL ////////////
$(document).on("click", "div a:nth-of-type(3)", function(e) {
e.preventDefault();
remove_all();
});
$("div a:nth-of-type(3)").click(remove_all);
///////// ADD ITEM ////////////
$(document).on("click", "#add_item", function(e) {
e.preventDefault();
console.log("Running Add Item.");
add_item();
});
$("#add_item").click(add_item);
///////// LOAD ALL ////////////
$(document).on("click", "div a:nth-of-type(2)", function(e) {
e.preventDefault();
load_all();
});
///////// REMOVE ITEM ////////////
$(document).on("click", "#my_list a", function(e) {
e.preventDefault();
var current_item = $(this).parent("li");
remove_item(current_item);
});
//$("#my_list a").click(remove_item(current_item));
///////// EDITABLE ITEM ////////////
});
/// CRUD FUNCTIONS ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
function add_item() {
if ($("#dialog-form").length == 0) {
console.log("Dialog not found, creating new Dialog.");
var newDialog = $("<div>", {
id: "dialog-form"
});
} else {
console.log("Dialog Found.");
var newDialog = $("#dialog-form");
newDialog.dialog("open");
return true;
}
newDialog.append("<label style='display: block;'>Add your item:</label><input type='text' id='new_item' />");
//$('body').append('<div id="dialog-form"><form> Add your item:<br><input type="text" name="new_item" id="new_item" ></form></div>');
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Add new item',
height: 240,
width: 260,
modal: true,
autoOpen: false,
buttons: [{
text: "Yes",
click: function() {
var test = $('#new_item').val();
console.log(test);
$("#my_list").append("<li>" + test + " <a href='#'>x</a></li>");
$(this).dialog("close");
$('#new_item').val("");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$('#new_item').val("");
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
}
function remove_all() {
$('#my_list li').remove();
}
function load_all() {
$.getJSON("myLists/myList.json", function(json) {
var items = json;
$('#my_list li').remove();
$.each(items, function(index, the_item) {
$('#my_list').append('<li>' + the_item + 'x</li>')
});
});
}
function remove_item(current_item) {
// APPEND DIALOG BOX DIV
$('<div id="dialog-confirm">').appendTo('body');
// JQUERY UI DIALOG
$("#dialog-confirm").dialog({
resizable: false,
title: 'Remove this item?',
height: 140,
width: 260,
modal: true,
buttons: {
"Yes": function() {
$(current_item).hide();
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
}
When removing an item, you want to pass the <li> to your function. This way it is removed from the <ul>.
When adding the item, I did not append the <div> to the body. I noticed when you appended the <div>, since it was not in the DOM when the page loaded, it does not get initialized as a .dialog() and thus is rendered into the HTML. My method avoids this.
Nothing wrong with the way you create the buttons, yet this is more specific and is how it is described by the UI API: http://api.jqueryui.com/dialog/#option-buttons
Hope this helps.

how to append more than one button with different id to a div by creating a single function

My task is to append button dynamically to a div .. and i want to apppend more than one button with different id to a single or different div by using a simple function. the below code that i have to used to append single button to a div..
<script type="text/javascript">
$(document).ready(function () {
addInputTo($(".myClass"));
$("#field").click(function () {
alert("hi");
$(".myClass").appendTo({
icons: {
primary: "ui-icon-locked"
},
});
});
});
function addInputTo(container) {
var inputToAdd = $("<input/>", {
type: "button",
id: "field",
value: "Test Button"
});
// var s="trype='button";
container.append(inputToAdd);
}
</script>
<div class="myClass"></div>
Is there any solution to append more than one button by creating single function like..
_app.CreateButton (id, text, primaryIcon, secondaryIcon, className);
please help me
and we use the below code to append icon to button but it dosen't work please help me
<script type="text/javascript">
function runEffect() {
debugger;
alert("1");
$( ".AdvSearchSaveButton" ).button({
icons: {
primary: "ui-icon-locked"
},
});
}
$(document).ready(function () {
$("#filed").click(function () {
alert("hi");
runEffect();
// $( "#filed" ).addClass( "ui-icon-locked" );
});
});
</script>
you can change the function addInputTo to
function addInputTo(container, id, text){
var inputToAdd = $("<input/>", { type: "button", id: id, value: text });
container.append(inputToAdd);
}
then call it using
addInputTo($(".myClass"), 'filed', 'test button');
This is really all you need. I just tied the event handler to the click of any <div> with the class = "myClass" with a self calling function.
HTML:
<div class="myClass" style="width:150px; height:150px;background-color:red;"></div>
Javascript:
var id=0;
$(function(){
$(".myClass").click(function(){
id++;
var newButton = "<input type='button' id='number" + id.toString() + "'value='test button'></input>";
$(this).append(newButton);
});
});
Just click on your <div> and a new button with a unique id will be appended to the <div>. Cheers!

Alert after second click

I have below code:
<a href="#" id="#item.Id" name="vote" ><img src="/Content/images/021.png" style="float:left" alt="" /></a>
which invokes an ajax call. on the first call. if the return is true, on the second call I want to make an alert box saying you can do vote only once.
<script type="text/javascript">
$(function () {
$("div.slidera_button a").click(function (e) {
var item = $(this);
e.preventDefault();
$.get('#Url.Action("VoteAjax","Home")', { id: item.attr("id") }, function (response) {
if (response.vote == "false") {
alert("foo.");
} else {
//something
}
});
})
});
</script>
this works, if i click on the button then refresh the page but it doesnt work, if i try to click twice.
I want to the user to be able to click multiple times and only after first one, they get a popup.
why this is not working?
how can i fix it?
EDIT: works in FF.. doesnt work in IE.
How about something like this:
<style type="text/css">
a.disabled {
opacity: 0.5;
/* whatever other styles you want */
}
</style>
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$("div.slidera_button a").click(function (e) {
var item = $(this);
if (item.hasClass("disabled")) {
// alert when they vote
// you'll need to handle some way to add this
// server side to account for page reload, yes?
alert('You may only vote once');
}
$.get('#Url.Action("VoteAjax", "Home")'
, { id: item.attr("id") }
, function (response) {
// if this returns successfully, you voted.
item.addClass('disabled');
}
});
return false;
})
});
</script>
Use this script
<script type="text/javascript">
$(function () {
$("div.slidera_button a").live('click',function (e) {
var item = $(this);
e.preventDefault();
$.get('#Url.Action("VoteAjax","Home")', { id: item.attr("id") }, function (response) {
if (response.vote == "false") {
alert("foo.");
} else {
//something
}
});
})
});
</script>
Or JQuery Delegate method to trigger this click

jQuery hidden field not getting set more than once

I'm trying to allow users to delete multiple records, they click a link "delete" and a dialog shows saying are you sure? On clicking OK it should delete.
It works for the first time I do it, but for any other delete buttons I click it doesn't work. I'm setting a hidden field to store some information then getting that information in the dialog.
I have identified the problem see comment in code, but not sure why its a problem.
This is for the delete buttons:
$(".delete-item").click(function () {
$(this).css('font-weight', 'bold');
var delId = $(this).attr("id");
$("#hidden-itemid").val(delId);
$("#dialog-delete-sure").dialog("open");
});
heres the dialog:
$("#dialog-delete-sure").dialog({
autoOpen: false,
resizable: false,
height: 140,
modal: true,
buttons: {
Ok: function () {
var hiddenId = $("#hidden-itemid").val();//*** This comes back undefined the second time***//
var itemId = $("#hidden-itemid").val().split('-')[1];
var iType = $("#hidden-itemid").val().split('-')[0];
$.post('/User/Delete/', { id: itemId, itemType: iType }, function (json) {
if (json.success) {
$("#" + iType + "-row-" + itemId).hide('slow', function () { $("#hidden-itemid").remove(); });
$("#dialog-success-delete").dialog("open");
} else {
if (json.error == "unknown") {
$("#dialog-unknown-error").dialog("open");
}
if (json.error == "unauthenticated") {
$("#dialog-unauthenticated").dialog("open");
}
}
});
$("#hidden-itemid").css('font-weight', 'normal');
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
a typical delete button looks like this:
<a id="event-63" class="delete-item">Delete</a>
any ideas?
You are running
$("#hidden-itemid").remove();
on json.success so you remove the element from the DOM .. next time it does not exists and thus you get an error..

Categories