jQuery UI modal confirmation dialog with ASP.NET not firing onClick event - javascript

jQuery newbie here. I've looked at dozens of similar questions on this site, as well as the answers provided so far here, all having pretty much the same response, and I've tried all of them, but nothing is working for me.
For the Javascript code in my .aspx, I currently have:
<script type="text/javascript" src="/resources/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.8.20.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.8.20.custom.css" />
<script language="javascript" type="text/javascript">
$(function() {
var $myDialog = $("#cancelDialog").dialog({
autoOpen: false,
modal: true,
buttons: {
'Yes, cancel': function() {
$(this).dialog('close');
return true;
},
'No, resume editing': function() {
$(this).dialog('close');
return false;
}
}
});
$("[id$=btnCancel]").click(function(e) {
//e.preventDefault();
alert('boo');
//$myDialog.dialog('open');
});
});
</script>
The markup for "btnCancel" looks like this - notice that I don't have an "onClientClick" attribute because jQuery is supposed to do this for me, right?
<asp:Button ID="btnCancel" CssClass="btnCancel" runat="server" Text="Cancel"
CausesValidation="false" UseSubmitBehavior="false" />
And here's the markup I have for the cancellation dialog:
<div id="cancelDialog" style="display: none;" title="Please confirm cancellation">
<p>Are you sure you wish to cancel and abandon your changes?</p>
</div>
According to all the examples I've seen (and the answers provided here), this should give me a jQuery UI popup with my two buttons that just works. The page is no longer posting back when I hit the cancel button (due to the changes I made at Patrick Scott's suggestion). I could just use a standard Javascript confirm() dialog for this, but I want to be able to customize the prompts/styling.
The only other information I can think of to throw in is that this code is on an ASP.NET Wizard control (the cancel button is in the StepNavigationTemplate), but that shouldn't matter, should it?
Any hints as to what I need to change to get this working are greatly appreciated!
(question & code updated to reflect recent changes I've made)

The reason it isn't working is because the ID of the button changes when it's rendered to the page. To access the control in JavaScript, you need to use the ClientID property:
$("#<%= btnCancel.ClientID %>").click(function(e){
//open the dialog
});

Use $("[id$=btnCancel]") as your selector for the click event..
$= means ends with in the jquery selector, and webforms adds a bunch of stuff that will make your id not match.
$("[id$=btnCancel]").click(function(e) {
I also don't understand why you have the buttons declared separately from the rest of the dialog...
do this instead:
$(function() {
var $myDialog = $("#cancelDialog").dialog({
autoOpen: false,
modal: true,
buttons: {
'Yes, cancel': function() {
$(this).dialog('close');
return true;
},
'No, resume editing': function() {
$(this).dialog('close');
return false;
}
}
});
$("[id$=btnCancel]").click(function(e) {
e.preventDefault();
$myDialog.dialog('open');
});
});

you need to break it down - it sounds like there is another error in the JS somewhere which you don't see because the page is reposting. Try an alert on the click:
$('#btnCancel').click(function(e) {
alert('boo');
});
If this doesn't work you need to make the simplest script possible get that working and then add to it.

I figured it out! It turns out that <script> tags (nor most other tags, it seems) cannot be self-closed in HTML4 or HTML5. I was writing them like so:
<script type="text/javascript" src="whatever" />
when according to the standard, they must be written like so:
<script type="text/javascript" src="whatever"></script>
This was allowing my first <script> include to work (jquery-1.7.2.min.js), but following ones to fail. Weird, huh?
Here are some links with supporting information:
http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.1 (the HTML4 specification)
Can the <script> tag not be self closed?
http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/

<%=this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this.Button1))%>;
Hook this to the "yes" button on your modal confirmation dialog. You'll need to change the ID according to your needs.

Related

Manipulate webpage based on user selection of popup window in asp.net website using JavaScript?

I have an asp.net website. I want to open a popup asking for user confirmation in code behind page.
I have a drop down with some values. "cancel ticket" is one of those values. So when user selects this item, I want to display a confirmation box asking user "Are you sure you want to cancel the ticket"?
I've tried some code using JavaScript,
HTML:
<asp:DropDownList ID="ddlStatus" runat="server" CssClass="selectstyle" DataTextField="Name" DataValueField="ID" onchange ="GetSelectedItem(this);" />
JavaScript :
<script type="text/javascript">
function GetSelectedItem(x) {
if (x.value == 4) {
return confirm("Are you sure you want to cancel support ticket ?");
}
}
which is displaying a popup as I want.
Now, I want to make a textbox and a label visible if user clicked on "OK" and reset dropdownlist if user clicked on "Cancel"
I've found this, i hop this help you
http://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx
You would use
ClientScriptManager.RegisterClientScriptBlock
https://msdn.microsoft.com/en-us/library/bahh2fef%28v=vs.110%29.aspx
The right way to approach this is by checking the value and prompting the user in the client side via javascript (this will probably help you).
But if you insist on going through the server, you can either:
Do an ajax call and then prompt the user for confirmation,
or create another form/view to do that.
Try adding a bootstrap modal and injecting script like ClientScriptManager.RegisterClientScriptBlock (Type, String,"$(modal).modal('show')")
Do remember to add the bootstrap js and css
My suggestion is:
1- Create a invisible div with your cancel button (and/or others elements/controls you want)
<div id="div_dialog" style="display: none;" >
<h3>Do you want to cancel?</h3>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
</div>
2- Use jquery to use your drop down as a trigger and dialog your hidden div
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
// this will open the popup when drop donw change
//(aply your filter by selected item)
$("#<%=DropDownList1.ClientID%>").change(function () {
$("#div_dialog").dialog({
dialogClass: 'DynamicDialogStyle',
height: 160,
width: 220,
title: "My modal Dialog Popup",
modal: true
});
return false;
});
// this function will do the postback and fire the event in the popup button
$('#<%=Button1.ClientID%>').click(
function() {
<%=this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this.Button1))%>;
});
});
</script>
3- Instead of using ddlStatus_Tickets_SelectedIndexChanged event, handle your confirmation code in the confirmation button event click
protected void Button1_Click(object sender, EventArgs e)
{
// you code
}

HTML Form Submit disable and change text on click

Whats the best way to disable a HTML Form Submit button when it is clicked and also change the text value on it?
Someone recommended a Javascript onclick event, but I would instead recommend using onsubmit. This will be on the form itself rather than the button, and this encompasses the real event that you want to disable the button with (submission), as well as other events that could possibly trigger submit.
document.getElementById('FormId').addEventListener('submit',function(){
var button = document.getElementById('buttonId');
button.innerText = 'Something new!';
button.disabled = true;
});
Edited my answer to include the extra changes you were looking for (text of button, disabled as well).
Edit again: lets be super cross browser!
var form = document.getElementById('FormId');
function submitForm(){
var button = document.getElementById('ButtonId');
button.innerText = 'Something new!';
button.disabled = true;
}
if(form.addEventListener){
form.addEventListener('submit',submitForm,false);
} else {
form.attachEvent('onsubmit',submitForm);
}
This covers versions of IE prior to IE9. Obviously if you have more than one form you would try to make this a little more reusable, but this is the general gist.
The best way to achieve this is via JQuery.
Let say your form submit button has an id="submitButton". So add this script to you page head and refer the place where you put your downloaded JQuery and JQuery-UI script.
<script type="text/javascript" src="Scripts/jquery-2.0.3.js"></script>
<script type="text/javascript" src="Scripts/jquery-ui-1.10.3.js"></script>
<script>
function submitButton_OnClick() {
$("#submitButton").text("New Text");
$("#submitButton").attr("disabled", "disabled");
}
$(document).ready(function() {
$("#submitButton").click(submitButton_OnClick);
});
</script>
and this to your html
<button id="submitButton">test</button>
Check it work!
You can add an onclick event and implement a javascript function to do what you want. You can have a look here to see how to disable a button from javascript. Also take a look here for an example how to change the text of the button using javascript.
You have to use JavaScript and set on click event for example it should be:
HTML:
input type="button" value="value" id="1" onClick="OnClick(this.id)"/>
JavaScript:
function OnClick(id)
{
//some stuff...
}
Also you can use jQuery and catch on submit, for example:
$("form").on('submit',function(event)
{
event.preventDefault();
//some stuff...
}
You can use to onclick attribute to set the disabled attribute. Note that I don't cover how to reenable the button when form submission is complete.
<button type="submit" onclick="this.setAttribute('disabled', 'disabled');">Submit</button>
See the live example here at this fiddle:
http://jsfiddle.net/yinkadet/DPJGw/
I hope this helps
Here is my example of providing this functionality using Ruby on Rails and jQuery - it is an implementation example of the jQuery answer which i found very useful! (so there, haters):
<div class="col s12">
<div class="actions">
<%= f.submit nil, class: "waves-effect waves-light btn green darken-3", id: "gsb" %>
<script>
function submitButton_OnClick() {
$("#gsb").val("***CREATING***");
$("#gsb").attr("disabled", "disabled");
$("#new_group").submit();
}
$(document).ready(function() {
$("#gsb").click(submitButton_OnClick);
});
</script>
</div>
</div>

magnific-popup passing a variable

I'm trying to make magnific popup contain some forms. I would like to pass variables through the html anchor to the final popup.
As Var1 in this pseudocode:
<!-- HTML launcher element -->
Show inline popup
<!-- Popup itself -->
<div id="test-popup">
<form method="post" action="">
<input type="hidden" id="myVar" name="Var1" value="[placeholder]" />
<input type="submit" />
</form>
</div>
<!-- Inizialization -->
<script type="text/javascript">
$(document).ready(function() {
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true,
function() {
**Here some magic code that sets Var1 = X **
$('#myVar').attr('value', function(i, attr){
return attr.replace('[placeholder]', Var1);
});}
});
});
</script>
I need this because I will generate serverside (w. PHP) the launchers so that each link will generate different form data.
edit: One approach i thought at was to use custom attributes in the launcher, eg:
Show inline popup
But I couldn't really get the right jQuery syntax for nesting the attributes processing INSIDE the magnific-popup inizialization.
My js/jquery knowledge is very basic, so thank you for any hint.
How about using a separate click handler outside the magnificPopup settings that changes the value of your input whenever a link is clicked, just make sure to bind it before initializing the plugin
HTML
Using data attributes as correctly suggested
Show inline popup
Javascript
$('.open-popup-link').click(function(){
$('#myVar').val($(this).data('var1'));
});
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true
});
Try:
Javascript/jQuery
<script type="text/javascript">
$(document).ready(function() {
$('.open_popup_link').magnificPopup({
type:'inline',
midClick: true,
function() {
**Here some magic code that sets Var1 = X **
Var1 = $('#myVar').val();
});}
});
});
Not quite sure what you are using Var1 for, but that is how you would get the value from the input into a global Var1 variable.
Let me know if I didn't understand what you're trying to do correctly.

ajaxSubmit Form Validation with a pop-up "processing" div

I'm using ajaxSubmit on my web form. I also need to pop-up a div that shows "Processing the request" with a dimmed background upon user's click on the submit.
The code I'm using right now is like this:
<script type="text/javascript">
$(document).ready(function() {
$("#CustomerService").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "processor.aspx",
success : function() {window.location.replace("Thankyou.aspx")},
failure : function() {}
})
});
</script>
<script type="text/javascript">
function DimScreen()
{
document.getElementById("DimBlackScreen").style.visibility = "visible";
}
</script>
And my HTML part for the submit button:
<input type="submit" value="Submit" id="Send" name="Send" style="cursor:pointer;" onclick="DimScreen();" />
Well the problem here is: whether the form passes the validation or not, the pop-up div will always show up, which is not the case I want.
Is there any way to make it detect if the form validation has passed and then display the div?
Many thanks for your help.
If you are using jquery version 1.4 or above try this:
$(document).ajaxStart(function() {
$("#DimBlackScreen").show();
}).ajaxStop(function() {
$("#DimBlackScreen").hide();
});
or if you are using less version of jquery 1.4 try this
$().ajaxStart(function() {
$("#DimBlackScreen").show();
}).ajaxStop(function() {
$("#DimBlackScreen").hide();
});
Remember put all these stuff in document.ready
$(document).ready(function() {
$("input#Send").click(function(e){
e.preventDefault(); //prevent default submit action,, use ajax instead
$('#DimBlackScreen').show();
$("#CustomerService").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "processor.aspx",
success : function() {
$('#DimBlackScreen').hide();
window.location.replace("Thankyou.aspx"); //or $('body').html('Thank you!');
},
failure : function() {}
});// end validationEngine
}); //end click
});//end document.ready
<input type="submit" value="Submit" id="Send" name="Send" style="cursor:pointer;" />
Ok, inspired by the other two answers from alsahin and Kundan, I figured it out myself:
The only thing needs to be changed is how ajax handles the failure of validation. So I changed
failure : function() {}
to
failure : function() {document.getElementById("DimBlackScreen").style.visibility = "hidden";}
So that the pop-up "processing" div actually shows every time user clicks on the Submit button, but resets to hidden if the form doesn't pass validation.
I'm happy with my current code, but if you have any better ideas, please let me know.

Close colorbox from asp.net form Submit button in iframe

I'm aware there are other questions similar but I just cannot get this to work.
Id like to close the colorbox iframe on the click of a .NET Button form within the iframe.
<script type="text/javascript">
$(document).ready(function() {
$(".del-add").colorbox({ width: "800px", height: "660px", iframe: true, open: true });
});
</script>
Button
<asp:ImageButton ImageUrl="~/images/update_b.jpg" ID="but2" runat="server" OnClick="UpdateAddress" Visible="true" ValidationGroup="valEnquiry" />
If someone could be kind enough to spell it out to me in plain english that would be much appreciated.
thanks very much
This is what worked for me:
parent.$.colorbox.close();
You should make this your last line in "UpdateAddress" and return false so the page doesn't postback. If you need to postback then just after returning from postback invoke that line.
Try this
$("#<%=but2.ClientID%>").click(function(){
$.fn.colorbox.close();
});

Categories

Resources