How to Trigger LinkButton Postback after Confirmation using jQuery UI Dialog? - javascript

I want a LinkButton to popup a jQuery UI dialog that prompts the user to confirm the action. If the user hits OK, then I'd like the action to continue by posting back to the server.
I ended up creating two links: One is regular HTML that invokes my confirmation dialog. And the other is a regular LinkButton server control that is hidden, and that I want to invoke if the user confirms the dialog box.
The two links look like this:
<a id="preEnterOperations" href="#">
Enter Operations
</a>
<asp:LinkButton ID="lnkEnterOperations" runat="server"
OnClick="lnkEnterOperations_Click" Style="display:none">
Enter Operations
</asp:LinkButton>
And here's my JavaScript:
$(function () {
$('#preEnterOperations').on('click',
function (e) {
var confirmDialog = $('#enterOperationsConfirmationDialog');
confirmDialog.dialog({
modal: true,
buttons: {
Ok: function () {
confirmDialog.dialog("close");
confirmDialog.data('confirmed', '1');
$('#<%= lnkEnterOperations.ClientID %>').click();
},
Cancel: function () {
confirmDialog.dialog("close");
}
}
});
return false;
});
});
Everything seems right. The confirmation dialog pops up as expected. I can see my Ok handler runs if the user hits Ok. But the line $('#<%= lnkEnterOperations.ClientID %>').click(); doesn't do a thing! I've tried numerous variations on this line and the effect is always the same: nothing.
Can anyone help me see how I can execute a LinkButton postback if the user confirms the dialog box?

You can replace the following line:
$('#<%= lnkEnterOperations.ClientID %>').click();
With:
__doPostBack('<%= lnkEnterOperations.UniqueID %>', '');
That should do the trick.

Ok: function () {
confirmDialog.dialog("close");
confirmDialog.data('confirmed', '1');
$('#<%= lnkEnterOperations.ClientID %>').click(function(){
__doPostBack('<%= lnkEnterOperations.UniqueID %>', '');
});
},
Cancel: function () {
confirmDialog.dialog("close");
}
May be this can help.

You can replace "$('#<%= lnkEnterOperations.ClientID %>').click();"
with <%=Page.ClientScript.GetPostBackEventReference(lnkEnterOperations, "") %>

Related

Submit button does not work within popup window

I have a form within popup window something like that:
<div id="dialog" title="Rezerwacja">
<asp:TextBox ID="imieTextBox" runat="server" placeholder="ImiÄ™"></asp:TextBox>
<asp:TextBox ID="nazwiskoTextBox" runat="server" placeholder="Nazwisko"></asp:TextBox>
<asp:TextBox ID="emailTextBox" runat="server" TextMode="Email" placeholder="Email"></asp:TextBox>
<asp:TextBox ID="telefonKomorkowyTextBox" runat="server" TextMode="Phone" placeholder="Telefon kom."></asp:TextBox>
<div id="plansza"></div>
<asp:Button ID="rezerwujButton" runat="server" Text="Zarezerwuj" OnClick="rezerwujButton_Click" />
</div>
And JavaScript:
$(document).ready( function() {
$( "#dialog" ).dialog({
autoOpen: false,
show: {
effect: "puff",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$( ".opener" ).on( "click", function() {
$( "#dialog" ).dialog( "open" );
});
});
So I have to behind code:
protected void rezerwujButton_Click(object sender, EventArgs e)
{
rezerwacje nowaRezerwacja = new rezerwacje();
nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = telefonKomorkowyTextBox.Text;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();
}
And there is the problem, submit button "rezerwujButton" does not work. It look like a unclickable or something like that... I'm clicking on it and nothing do... Not refresh page or anything...
When I going to use that form without popup window, It work but within popup not.
I tried to set usesubmitbehavior="false" but when I did it, button worked, send something but every field was blank... I mean when i tried to get something like that: imieTextBox.Text It will be blank... Always...
Any ideas?
#edit
I don't know what Do I do wrong?
Always a fields from form is blank...
Anybody can tell me how can I use correct this __PostBack? Because I have to do something wrong...
I added to button UseSubmitBehavior="fase" and in function PageLoad I got something like that:
if (Page.IsPostBack)
{
rezerwacje nowaRezerwacja = new rezerwacje();
nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = telefonKomorkowyTextBox.Text;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();
}
For example imieTextBox.Text is always blank... I don't know why...?
edit
Im done. I change the way to get modal window. I used popup window which not moving modal div anywhere and It working.
The reason of the "nothing happens" behaviour is the fact that jQuery-UI dialog widget moves the DOM-element, which is converted to a dialog (in your case - $("#dialog")), to body. After this, the submit button is not inside a form tag anymore, and clicking it does not cause any submission.
It will still work if the whole form is inside the dialog content:
<div id="dialog" title="Rezerwacja">
<form ...>
...
<asp:Button ID="rezerwujButton" runat="server" Text="Zarezerwuj" OnClick="rezerwujButton_Click" />
</form>
</div>
You can try putting your rezerwujButton_Click method into PageMethods
[ScriptMethod, WebMethod]
public string RezerwujCall() {
// logic here
return "ok";
}
Then in your js:
<script type="text/javascript">
function rezerwuj_clicked() {
PageMethods.RezerwujCall(function (response) { if(response == "ok"){} }, function(response){ console.log("failed"); });
}
</script>
This will require to change OnClick="rezerwujButton_Click" into OnClientClick="rezerwuj_clicked()"

SweetAlert: block event like JavaScript Alert()

I have a function that asks users for confirmation when selecting a value from a Select dropdown. When using the regular JavaScript confirm(), the change event does not get the newly selected value without clicking on confirm. This can be seen in this Fiddle.
When a value is selected, and the user clicks cancel, the same value is shown in an alert dialog. When the user clicks confirm, the newly selected value is displayed.
However, I'd like to use SweetAlert. When changing the value with SweetAlert, the change happens without even selecting confirm or cancel. As demonstrated in this Fiddle. When a value is selected, an alert dialog is displayed right after selection, unlike with the pure JS Confirm() which blocks the event somehow.
I'd like to achieve the same effect as the JS confirm(), where the change event is not triggered while the user has not clicked confirm or cancel, when using SweetAlert.
Aside from both Fiddles which demonstrate the problem, here's the code I'm using:
Some simple HTML select:
<select id="dropdownId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
The JavaScript confirm() version (which does what it needs to do):
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Other changed code would be here...
} else {
$(this).val(prev_val);
return false;
}
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
And the SweetAlert version, where the change event should wait on the response of the SweetAlert dialog.
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
return swal({
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
return true;
} else {
$(select).val(prev_val);
return false;
}
});
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
Edit:
Moving the logic to the confirm handler of the dialog does not solve this issue. I'm using a framework (Apache Tapestry) which listens for a change event on the select. When using the solution as RRR stated, in this fiddle, the change event still happens. Which still causes it to fire an event to my backend, unlike with the JS confirm() which does not change the value until confirm was clicked.
Edit 2:
My problem doesn't really seem to be that clear. Here are the steps I undertake to try and show what the root of the problem is:
When using the JS confirm from this fiddle. The following happens:
I click on a value
It asks for confirmation
On confirm, it logs the new value. On cancel, it logs the original value.
When using the SweetAlert dialog, using this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel I can execute logic.
When using the SweetAlert dialog, as edited by RRR in this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel, it shows an alert
Both my and RRR's SweetAlert example have the same issue. Namely, step 2. Not the fact that it logs, but the fact that the value actually changes. Unlike in the first pure JS example, where the value does NOT change unless confirm is clicked.
Ok. Here is the issue.
You call 2 different actions at onchange event:
1- The big function...
2- A test alert.
Both occur at the same time. <-- Here lies the confusion!
This is why it appeared to you that swal doesn't "wait" to get an answer from the user.
Try this... And look at your console.log messages:
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
console.log("On focus event value : "+prev_val); // ADDED
}).change(function (e) {
var select = this;
console.log("At the BEGINNING of the change event : "+$(select).val()); // ADDED
$(this).blur();
swal({ // REMOVED return in front of it
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true, // These are default.. useless to specify
closeOnCancel: true // These are default.. useless to specify
},
function (isConfirm) {
if (isConfirm) {
//return true; // no need to return anything - commented out
console.log("swal YES");
console.log("At the END of the change event : "+$(select).val());
} else {
$(select).val(prev_val);
//return false; // no need to return anything - commented out
console.log("swal NO");
console.log("At the END of the change event : "+$(select).val());
}
// Here is a callback final test alert!
alert("Callback alert: "+$(select).val());
});
});
/*$('#dropdownId').change(function (e) { // This was a bad idea ! ;)
alert($(this).val());
});*/
In my case sweet alert 2 was blocking my binded event handlers:
Swal.fire( // Not works - Nothing will happen onclick
{html: `<button id="btn1" onclick="alert('clicked')">Delete</button>`,
)
So i binded the event handlers in javascript instead, on modal open:
Swal.fire(
{html: `<button id="btn1">Delete</button>`,
onOpen: () => {document.querySelector('#btn1').onclick = () => {alert('clicked')}
)

How to detect button value change in JQuery?

I've a sign up form which has submit button with value "GET INSTANT ACCESS!" :
<input type="submit" class="wf-button" name="submit" value="GET INSTANT ACCESS!">
After submit, the value gets change to 'Thank You!':
<input type="button" class="wf-button" value="Thank You!">
I need to detect the button value. If it becomes "Thanks You!" then I have to show a popup. And this value gets change by some Ajax (GetResponse form). There is no page refresh.
I've tried below code but it is only working in FireFox & not working in Chrome.
<script>
$(function() {
$(".modalbox").fancybox();
});
$(function() {
$('.wf-button').bind("DOMSubtreeModified",function(){
//if btn valu is 'Thank You! trigger popup'
$(".modalbox").trigger('click');
});
});
</script>
Live URL: http://www.idynbiz.com/web/html/gold_ira_vf/? (just to show how the button changes its value)
Can some one help how can I detect the button value and show my popup? The button change its value in real time (Ajax). There is not page refresh.
Is there any JQuery approach with bind() Or on() function to detect the value?
$(function() {
$('.btn1').on('change', function() {
alert('Do stuff...');
});
$('.lnk1').on('click', function() {
$('.btn1').val('Thank you!');
$('.btn1').trigger('change');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="submit" class="btn1" value="SUBSCRIBE" />
Change button value
OK ,
when button is clicked and form is submitted for saving. just write these code
$(document).ready(function ()
{
$('.wf-button').click(function ()
{
var valueofbutton = $(this).attr('value');
if(valueofbutton == 'Thank You!')
{
window.open(); //// whatever you want to open in popup
}
});
});
i m sure that this will work
You can use the following function in javascript which gets called after any > kind of postback, i.e. synchronous or asynchronous.
function pageLoad()
{
if($(".wf-button").val()=="Thank You!")
{
// show your popup
}
}
Hope it works....

How does user confirmation message box work in ASP.Net

How does the client know to send request to server only when the confirmation box result is ok and stay on page if cancelled?
Also, is this mechanism any different in ASP.Net and ASP.Net MVC?
The responses I got seem to tell me how to implement the functionality.
I want to know the internal working of when user clicks OK/cancel what happens internally. How does browser come to know it has to proceed to server call or close itself and do nothing?
You can use simple confirm box
$("#callConfirm").on("click", function(e) {
if(confirm('Are you sure'))
alert('Yes');
else
alert('No');
});
JSFIDDLE
Try This
<script>
function CallConfirm()
{
if(confirm('Are you sure'))
//do your stuff
else
return false;
}
<script />
and on asp button write like this
<asp:Button id="Click" runat="server" onclientclick="return CallConfirm();" onclick="btn_Click"/>
you can use bootstrap in asp.net and it will help you give new look and help you in lots of other things,see this http://getbootstrap.com/ and u can use bootstrap confirmation box.
<asp:button
id="Button1" runat="server" text="Button" xmlns:asp="#unknown">OnClientClick="return confirmation();" onclick="Button1_Click"/>
</asp:button>
<script type="text/javascript">
function confirmation() {
if (confirm('are you sure you want to delete ?')) {
return true;
}else{
return false;
}
}
</script>
I write this Jquery code in the aspx page for button.
Steps:
Add a button for which you want to have a confirm box, add its jquery and div to show the confirm box.
Register the script for button on Page_Load, and write the methods which will bind this script on button.
Also do not forget the server side method or event for button click, which will be continued after OK confirmation from confirm box.
If cancel is clicked, nothing will happen and div will be closed.
<script type="text/javascript">
function FileItem(callBackFunction, title, content) {
$("#File-confirm").html(content).dialog({
autoOpen: true,
modal: true,
title: title,
resizable: false,
height: 140,
close: function (event, ui) { $(this).dialog("destroy"); },
buttons: {
'Ok': function () {
callBackFunction(); $(this).dialog("destroy");
},
'Cancel': function () {
$(this).dialog("destroy");
}
});
}
}
where SaveBtn is the button in the UI:
<asp:Button ID="SaveBtn" runat="server" Text="File" OnClick="SaveBtn_Click"/>
<div id="File-confirm" style="display: none">
</div>
Again the code behind:
FileConfirmRequest(SaveBtn, "Confirm", "Are you sure you want to file the changes?");
// In the Page_Load, write the above code
//Use this method later on the page
protected void FileConfirmRequest(Button control, string title, string message)
{
string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
string function = String.Format("javascript:FileItem(function() {{ {0} }}, '{1}', '{2}'); return false;", postBackReference, title, message);
control.Attributes.Add("OnClick", function);
}
Now, The Onclick of the Button:
protected void SaveBtn_Click(object sender, EventArgs e)
{
//Do what you want to after OK Click from the confirm box
}

Unable to get javascript to do button click from child iframe

I'm playing around with the Jquery UI dialog. I have a page with a gridview, a button that refreshes the gridview and a link. When you click a link, a dialog window popup up with the details of the record.
When I press save on the child page, I have the child page calling a javascript function from the parent page. In this function, it tried to do the button click event but it doesn't seem to be working.
If you look at the showThanks function below,
The alert works, the button text changes but the button click doesn't work.
Could this be a security feature? Both pages are on the same page right now.
hmm any clue?
Thanks
Edit - if you click the button manually, it changes the grid (in the button event handler). Yet, the jquery doesn't seem to be going in the button's event handler and the grid doesn't change.
Parent page html
<asp:GridView ID="gv" runat="server" />
<asp:Button ID="btnRefresh" runat="server" />
<a id="popoutUsers" href="popup.aspx?page=Bob" class="OpenNewLink">CLICK ME</a>
<script type="text/javascript">
$(function () {
$('.OpenNewLink').click(function () {
var url = $(this).attr('href');
var dialog = $('<div id="modal"></div>').appendTo('body')
$('<iframe id="site" src="' + url + '" />').dialog({
modal: true
, close: function (event, ui) {
// remove div with all data and events
dialog.remove();
}
});
return false;
});
showThanks = function () {
alert("Thanks");
var button = $("#btnRefresh");
button.val("hello"); //This works
button.click(); //Nothing seems to happen
// button.trigger("click"); (Tried trigger as well but no luck)
};
});
</script>
Child page
<div>
Why hello there
<asp:Button ID="btnBob" runat="server" Text="click me" />
</div>
<script type="text/javascript">
$(function () {
$('#btnBob').click(function (e) {
e.preventDefault();
window.parent.showThanks();
window.parent.$('.ui-dialog-content').filter(function () { return $(this).dialog('isOpen'); }).dialog('close');
return false;
});
});
</script>
So decided to do a new round of google searching and found this link Html Button that calls JQuery and does not post back
I changed my button to the following (added the UseSubmitBehavior)
and now it works. Hopefully I didn't waste people's time...

Categories

Resources