I have a wordpress auction site and wanted to add a confirm dialog with jquery when someone clicks on the "bid" button. I can achieve this with the default system dialog but I want a more custom dialog box with jQuery. How can I make it click the bid button once the end user has confirmed the bid?
Here is the code example:
<button type="submit" class="bid_button button alt"><?php echo wp_kses_post( apply_filters( 'bid_text', esc_html__( 'Bid', 'auctions-for-woocommerce' ), $product ) ); ?></button>
<script>
jQuery('button').confirm({
title: 'titletext',
content: 'content text"',
type: 'red',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-primary',
keys: ['enter'],
action: function(){
console.log('Brukeren bekreftet "OK"');
}
},
No: function(){
text: "No",
jQuery.alert('Kansellert!');
console.log('the user clicked cancel');
}
}
});
</script>
it seems like this libary is not created for submitting forms via button, more like using it for <a> tags, source - https://github.com/craftpip/jquery-confirm/issues/229
I thought i will give you still a way to solve your problem.
now i am preventing the default behavior from the button when its not confirmed and trigger it again when its confirmed, but this time the button can submit the form.
Also added the id submitButton to your button for making it individual.
<button type="submit" id="submitButton" class="bid_button button alt"></button>
<script>
var confirmed = false;
$('#submitButton').on('click', function() {
if (!confirmed) {
event.preventDefault();
$.confirm({
title: 'titletext ',
content: 'content text"',
type: 'red',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-primary',
keys: ['enter'],
action: function() {
confirmed = true;
$('#submitButton').click()
console.log('Brukeren bekreftet "OK"');
}
},
No: function() {
text: "No",
jQuery.alert('Kansellert!');
console.log('the user clicked cancel');
}
}
})
} else {
confirmed = false
}
})
</script>
hope I could help you. :)
Before moving my kendo-ui grid inside a bootstrap modal I would click on Add Row and the first of 3 inputs would be selected. I would then tab to the 2nd, then 3rd and then tab to the checkbox button where I would press enter and the row would be added. Then the focus would go back to the Add Row button to where I could press enter to start process over again. Well now that it is inside a modal I lost everything except for tabbing. I have found solutions that use jquery to apply focus but I already have that inside my grid controller.
Kendo-ui grid controller
$scope.mainGridOptions = {
dataSource: dataSource,
pageable: false,
toolbar: [{ name: "create", text: "Add Product", }],
columns: [
{ field: "product", title: "Product", width: "95px", editor: productEditor },
{
field: "price", title: "Price", width: "95px", format: "{0:c2}", editor: priceEditor
},
{
field: "sqft", title: "Square Feet", width: "95px", editor: sqftEditor
},
{
command: [{ name: 'edit', text: { edit: '', update: '', cancel: '' }, width: '20px' }, { name: 'destroy', text: '' }], title: ' ', width: '80px'
}],
editable: 'inline'
};
function productEditor(container, options) {
$('<input id="product" name="product" data-bind="value:product" data-productvalidation-msg="Put the Product!" />')
.appendTo(container)
.kendoMaskedTextBox({});
$("#product").focus(function () {
var input = $(this);
setTimeout(function () {
input.select();
});
});
};
function priceEditor(container, options) {
$('<input id="price" name="price" data-bind="value:price" data-step="10000" style="" data-productvalidation-msg="Put the Price!"/>')
.appendTo(container)
.kendoNumericTextBox({ format: 'c0', min: 0 });
$("#price").focus(function () {
var input = $(this);
setTimeout(function () {
input.select();
});
});
}
function sqftEditor(container, options) {
$('<input id="sqft" name="sqft" data-bind="value:sqft" data-step="500" style="" data-productvalidation-msg="Put the Sqft!"/>')
.appendTo(container)
.kendoNumericTextBox({ format: '0', min: 0 });
$("#sqft").focus(function () {
var input = $(this);
setTimeout(function () {
input.select();
});
});
};
Modal
<!-- Grid Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<div style="width:100%"><span class="modal-label">My Product Data</span><button style="float:right" class="btn btn-custom waves-effect" data-dismiss="modal"><i class="zmdi zmdi-close"></i></button></div>
</div>
<div class="modal-body">
<div kendo-grid id="grid" options="mainGridOptions"></div>
</div>
</div>
</div>
</div><!--End Grid Modal -->
Function to open modal
$scope.openGrid = function () {
$('#myModal').modal('show');
};
On the API Functions for NumericTextBox Kendo-UI control it shows that focus can be obtained by performing the following pseudo-code:
var numerictextbox = $("#numerictextbox").data("kendoNumericTextBox");
numerictextbox.focus();
So applying this to your code it would look something like this:
var price= $("#price").data("kendoNumericTextBox");
price.focus();
Additionally since your modal popup is more of an application I would suggest switching the accessability attributes from
role="document" to role="application"
I think the focus is hijacked from the bootstrap modal itself, you can use the shown event and set the focus accordingly.
Ref:
Bootstrap provides custom events for most plugins' unique actions.
Generally, these come in an infinitive and past participle form -
where the infinitive (ex. show) is triggered at the start of an event,
and its past participle form (ex. shown) is triggered on the
completion of an action.
As of 3.0.0, all Bootstrap events are namespaced.
All infinitive events provide preventDefault functionality. This
provides the ability to stop the execution of an action before it
starts.
Code:
$('#myModal').on('shown.bs.modal', function () {
//your current focus set
});
Try this… in show modal window
this.$workModal.on('show.bs.modal', (e) => {
$('#workId_input').data('kendoNumericTextBox').focus();
});
on UI.... You need to have ID on input…
<input id='workId_input', data-bind="kendoNumericTextBox ......">
Try this.. you just need to turn off Event Listener attached by Bootstrap.
$('#myModal').on('shown.bs.modal', function() {
$(document).off('focusin.modal');
});
Currently working on a personal project. I want the user to click a button and a SweetAlert prompt would be presented for the user to verify their credential. However, the code I see on the SweetAlert website only allows one input field. Here is the code I have:
swal({
title: "Authenicating for continuation",
text: "Test",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
}, function(inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
// swal("Nice!", "You wrote: " + inputValue, "success");
});
So, is there a way I can get two input fields? One input field for the password and the other input field for text.
Now SweetAlert2 is available:
https://sweetalert2.github.io
As per their info on bottom:
Multiple inputs aren't supported, you can achieve them by using html
and preConfirm parameters. Inside the preConfirm() function you can
pass the custom result to the resolve() function as a parameter:
swal({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
preConfirm: function () {
return new Promise(function (resolve) {
resolve([
$('#swal-input1').val(),
$('#swal-input2').val()
])
})
},
onOpen: function () {
$('#swal-input1').focus()
}
}).then(function (result) {
swal(JSON.stringify(result))
}).catch(swal.noop)
Multiple inputs aren't supported, you can achieve them by using HTML and preConfirm parameters.
Inside the preConfirm() function you can return (or, if async, resolve with) the custom result:
function sweetAlert(){
(async () => {
const { value: formValues } = await Swal.fire({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
focusConfirm: false,
preConfirm: () => {
return [
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]
}
})
if (formValues) {
Swal.fire(JSON.stringify(formValues))
}
})()
}
body {
font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9.3.4/dist/sweetalert2.all.min.js"></script>
<button onclick="sweetAlert()">Try me!</button>
Source: INPUT TYPES
You can have inputs in the default SweetAlert type, as long as you set the html property to true. The issue is that unless the type is set to "input", SweetAlert adds a display: none to input fields.
It's a bit of a workaround, but you can change this in the js file from
<input type=\"text\" tabIndex=\"3\" />\n
to
<input id=\"swalInput\" type=\"text\" tabIndex=\"3\" />\n
And change the css file from
.sweet-alert input {
to
.sweet-alert #swalInput {
Then you can simply add your html to the text parameter when calling, like so:
swal({
title: "Log In to Continue",
html: true,
text: "Username: <input type='text'><br>Password: <input type='password'>"
});
This method simply specifies that the only input to be styled that way is the one generated by SweetAlert, so that any inputs you add to your text won't be affected by that styling.
Using the example posted by Tikky in their answer above and based on the question asked for validation on that answer. You could possibly try the following to implement validation on this method:
swal({
title: 'Multiple inputs',
html:
'<input id="swal-input1" class="swal2-input">' +
'<input id="swal-input2" class="swal2-input">',
preConfirm: function () {
return new Promise(function (resolve) {
// Validate input
if ($('#swal-input1').val() == '' || $('#swal-input2').val() == '') {
swal.showValidationMessage("Enter a value in both fields"); // Show error when validation fails.
swal.enableConfirmButton(); // Enable the confirm button again.
} else {
swal.resetValidationMessage(); // Reset the validation message.
resolve([
$('#swal-input1').val(),
$('#swal-input2').val()
]);
}
})
},
onOpen: function () {
$('#swal-input1').focus()
}
}).then(function (result) {
// If validation fails, the value is undefined. Break out here.
if (typeof(result.value) == 'undefined') {
return false;
}
swal(JSON.stringify(result))
}).catch(swal.noop)
As far as I know you can't do this off-the-shelf. You can either fork and implement, or just use a HTML element as a modal (e.g. as in Bootstrap's modals).
$(document).ready(function(){
$("a").click(function(){
swal({
title: "Teste",
text: "Test:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "User"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("Error");
return false;
}
swal({
title: "Teste",
text: "E-mail:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Digite seu e-mail"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("E-mail error");
return false;
}
swal("Nice!", "You wrote: " + inputValue, "success");
});
});
});
});
Multiple inputs aren't supported, you can achieve them by using html and preConfirm parameters.
Notice that in preConfirm function you can pass the custom result to resolve():
You can do this using such manner:
swal({
title: 'Multiple inputs',
html:
'<h2>Login details for waybill generation</h2>'+
'<input id="swal-input1" class="swal2-input" autofocus placeholder="User ID">' +
'<input id="swal-input2" class="swal2-input" placeholder="Password">',
preConfirm: function() {
return new Promise(function(resolve) {
if (true) {
resolve([
document.getElementById('swal-input1').value,
document.getElementById('swal-input2').value
]);
}
});
}
}).then(function(result) {
swal(JSON.stringify(result));
})
}
The link here: https://limonte.github.io/sweetalert2/
It's very simple through the preConfirm method and using ok button as submission button in sweetalert2
swal.fire({
showCancelButton:true,
html:`input1:<input id="input1" type="text">
input2: <input id="input2" type="text">
input3: <input id="input3" type="text">`,
preConfirm:function(){
in1= $('#input1').val();
in2= $('#input2').val();
in3 = $('#input3').val();
console.log(in1,in2,in3) // use user input value freely
}
})
Here is an example using sweetalert#^2.1.0, showing one way to have multiple input fields. The example uses jQuery, but jQuery is not required for this technique to work.
// ==============================================================
//swal does not block, and the last swal wins
//so these swals are closed by later calls to swal, before you can see them
// ==============================================================
swal("aaa");
swal("bbb");
// ==============================================================
//for multiple inputs, use content: anHtmlElement
// ==============================================================
const div = document.createElement("div");
console.log(div);
$(div).html("first<input id='111' value='one'></input></br>second<input id='222' value='two'></input></br>third<input id='333' value='three'></input>");
swal({
title: "Three Inputs",
content: div,
// ==============================================================
//true means show cancel button, with default values
// ==============================================================
buttons: [true, "Do It"]
}).then(value => {
if (value) {
const outputString = `
value is true for confirm (i.e. OK); false for cancel
value: ${value}
` + $("#111").val() + " " + $("#222").val() + " " + $("#333").val();
// ==============================================================
// there are no open swals at this point, so another call to swal is OK here
// ==============================================================
swal(outputString);
} else {
swal("You cancelled");
}
});
alert("swal is not blocking: " + $("#111").val() + " " + $("#222").val() + " " + $("#333").val());
Try this way
swal({
text: 'First Input',
content: "input",
button: {
text: "Add New",
closeModal: false,
},
})
.then(name => {
swal({
text: 'Second Input',
content: "input",
button: {
text: "Add New",
closeModal: false,
},
}).then(id => {
//save code here.
})
}).catch(err => {
swal("Error");
});
On SweetAlert 2.x you can use this vanilla Javascript for getting / setting one input. Yo can chain more elements to content so you can have multiple inputs:
var slider = document.createElement("input");
slider.type = "number";
slider.value = 5;
slider.step=1;
slider.min = 5;
slider.max = 50;
this.swal({
title: 'Request time to XXX',
text: 'Select values',
content: slider,
buttons: {
cancel: "Run away!",
catch: {
text: "Throw Pokéball",
value: slider.value,
},
defeat: true,
}
}).then((value) => {
console.log(slider.value); // Here you receive the input data value
//swal(`You typed: ${value}`);
});
check this out
https://sweetalert2.github.io/
"AJAX request example" + "Chaining modals (queue) example" has inputs and you can work with them
Email and Password login double input boxes in Asp.Net Core MVC with ajax to clear application session and relogin to reassign session. The "sweetModal" function should be called in javascript for application 5mins idle timer trigger for the sweetalert modal popup. Adjust to suit your need. Please note, this applies to SweeetAlert 2.0 of https://sweetalert.js.org/ and jQuery v3.5.1
sweetModal = () => {
swal({
icon: '../../../images/yourlogo.png',
title: 'Relogin',
content: {
element: "input",
attributes: {
placeholder: "Enter username",
},
},
buttons: {
confirm: {
text: "Submit",
value: true,
visible: true,
className: "",
closeModal: false
},
cancel: {
text: "Cancel",
value: null,
visible: true,
className: "",
closeModal: true
},
},
closeOnClickOutside: false,
closeOnEsc: false,
})
.then((user) => {
if (user) {
swal({
icon: '../../../images/yourlogo.png',
title: 'Relogin',
content: {
element: "input",
attributes: {
placeholder: "Enter password",
type: "password",
},
},
buttons: {
confirm: {
text: "Submit",
value: true,
visible: true,
className: "",
closeModal: false
},
cancel: {
text: "Cancel",
value: null,
visible: true,
className: "",
closeModal: true
},
},
closeOnClickOutside: false,
closeOnEsc: false,
})
.then((pwd) => {
if (pwd) {
$.post("/account/refreshsession", { user: user, pwd: pwd }, () => swal(`Successful!`));
//swal(`The returned value is: ${user} ${pwd}`);
}
});
}
});
}
The way I add 2 or more input fields is; I set html to true and use text to write you inputs, just make sure to add the class "show" (display: block) to your inputs. Swal will hide your inputs. Example:
swal({
title: "Test",
html: true,
text: ` <input class="show" tabindex="1" placeholder="">
<input class="show" tabindex="1" placeholder="">
`
}
This is working in my case
swal({
title: "Update Score",
// type: "input",
// inputPlaceholder: "Home",
showCancelButton: true,
// cancelButtonText: "Cancel",
// closeOnConfirm: false,
// closeOnCancel: false
html: true,
text: '<input id="input1" type="text" placeholder="Home" style="display:block !important;"><br><input id="input2" type="text" placeholder="Away" style="display:block !important;">',
},
function () {
in1 = $('#input1').val();
in2 = $('#input2').val();
alert(in1 + " = " + in2)
});
Yes you can!!!
swal({
title: "An input!",
text: "Write something interesting:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top",
inputPlaceholder: "Write something"
},
function(inputValue){
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false
}
swal("Nice!", "You wrote: " + inputValue, "success");
});
I´m trying create a bootstrap popup with bootbox modal, inside of form has a input text with masked input, but any events inside of popup don´t work.
See here: http://jsfiddle.net/ens1z/UK6x5/5/
The html:
<p>The mask input below WORKS great</p>
<p>
<input type="text" class="mask" />
</p>
OPEN BOOTBOX
<div id="frm" style="visibility: hidden">
<div class="form-horizontal">
<p>The mask input below DON´T WORK. :-(</p>
<input type="text" class="mask"/>
</div>
</div>
JavaScript:
$("#asssf").click(function (e) {
e.preventDefault();
bootbox.dialog({
message: $("#frm").html(),
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-danger",
callback: function() {
return;
}
}
}
});
$(".mask").mask("999-99-9999",{placeholder:"_"});
});
$(".mask").mask("999-99-9999",{placeholder:"_"});
How to mask works inside of popup?
Try this fiddle :) HERE
The problem is that you loaded the html to bootbox without his events.
i made a function to solve your problem:
function BootboxContent(){
var content = $("#frm").clone(true);
$(content).css('visibility','visible');
content.find('.mask').mask("999-99-9999",{placeholder:"_"});
return content ;
}
call it on your message as in the fiddle, or without function like this :
bootbox.dialog({
message: $("#frm").clone(true).css('visibility','visible').find('.mask').mask("999-99-9999",{placeholder:"_"}),
title: "Custom title",
buttons: {
success: {
label: "Success!",
className: "btn-danger",
callback: function() {
return;
}
}
}
});
});
I know the correct way to manage JQuery.dialog is to initialize with:
$("#dialog").dialog({ autoOpen: false });
Then use the following to open and close it:
$("#dialog").dialog("open");
$("#dialog").dialog("close");
But there are some cases when this model is not fully applicable.
For instance, I use a dialog to create new data and to edit existing data. In the first case I have a cancel and a create button, but in the second case I have also a delete button.
I've seen that there is a destroy function in jquery.dialog. The question is: in these cases, should I destroy the dialog instead of close it and create a new one? There is any better option?
jQuery UI dialog allows you to manipulate most properties after initialization. You can change the buttons some time after the dialog is initialized; e.g. when the insert or update button is clicked.
// imported from http://jsfiddle.net/salman/VYAJw/9/
$(function() {
$("#dialog1").dialog({
autoOpen: false,
modal: true
});
$("#button-insert").click(function() {
$("#dialog1").dialog("option", "title", 'Insert Record');
$("#dialog1").dialog("option", "buttons", [{
text: "Insert",
click: function() {
alert("Record inserted");
$(this).dialog("close");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}]);
$("#dialog1").dialog("open");
});
$("#button-update").click(function() {
$("#dialog1").dialog("option", "title", 'Update Record');
$("#dialog1").dialog("option", "buttons", [{
text: "Update",
click: function() {
alert("Record updated");
$(this).dialog("close");
}
}, {
text: "Delete",
click: function() {
alert("Record deleted");
$(this).dialog("close");
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}]);
$("#dialog1").dialog("open");
});
});
#import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");
body {
font: medium sans-serif;
}
#dialog1 label,
#dialog1 input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="dialog1">
<p>Fill out this form.</p>
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</fieldset>
</form>
</div>
<input type="button" id="button-insert" value="Insert" />
<input type="button" id="button-update" value="Update" />
An alternate method would be to add the buttons directly inside the form and .hide() them depending on whether you're showing insert or update dialog.
you can set different buttons as option before dialog open
e.g.
var buttons = {
"act_add": {
"Insert": function() { ... },
"Cancel": function() { ... }
},
"act_edit": {
"Save": function() { ... },
"Delete": function() { ... }
}
};
$('.dialogOpenLink').click(function(){
var $dlg = $('#dialog'),
actType;
//get an action name from data attribute of the clicked element
actType = $(this).data('action'); //or get the action in way that best suits you
$dlg.dialog( "option", "buttons", buttons[actType]);
$dlg.dialog('open');
});
To safelly remove dialog all you need is to set close option like this:
close: function() {
return $(this).remove();
}