My javascript click event run on second click but not on first - c#

function loadToFalloutPopup() {
$('#fallout-all-modal').modal({
backdrop: true,
keyboard: true
});
}
$document.on('click', '.all-fallout-btn', loadToFalloutPopup)
});
Html:
<button type="button" class="all-fallout-btn" data-dismiss="modal">To Fallout</button>
JQuery click event fires on second click but not on first. I dont know what is gong on, please help.

Try this:
function loadToFalloutPopup() {
$('#fallout-all-modal').modal({
backdrop: true,
keyboard: true
});
}
$(document).ready(function() { // always write any event on $(document).ready
$(document).on('click', '.all-fallout-btn', function() { // use click event like this
loadToFalloutPopup();
});
})

Try this
$(document).on('click', '.all-fallout-btn', function(){
loadToFalloutPopup()
});
var count=0
function loadToFalloutPopup() {
count++
$('#spanCount').text(count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="all-fallout-btn" data-dismiss="modal">To Fallout</button><br/><span id='spanCount'>0</span>

Related

JQuery client side continues even if invalid mvc 4

Script
$(document).ready(function () {
"use strict";
$.validator.unobtrusive.parse($("#form"));
$("#submit").on("click", function () {
var form = $("#form");
form.validate();
if (form.valid()) {
}
return false;
});
});
HTML
<span>Please enter the amount of orders you wish you process:</span>
<br>
#Html.TextBoxFor(m => m.OrderModel.AmountOfOrders, new {id = "AmountOfOrders"})
#Html.ValidationMessageFor(m=> m.OrderModel.AmountOfOrders)
<input type="submit" value ="Submit" id="submit" />
I seem to have a problem with the script. The DataAnnotations for C# are showing up on the View but even if required fields are empty it will still continue to the other page.
if your button is not given
type="button"
, it will default to
type="submit"
Considering that you are using a form, the form will get submitted by the button click as your javascript is executing.
Try this.
$("#submit").on("click", function (event) {
var form = $("#form");
form.validate();
if (form.valid()) {
}
else
{
event.preventDefault();
return false;
}
});
Always use the submit event for forms, not the click event. That way it will work with key-presses:
$("#submit").on("submit", function () {
var form = $("#form");
form.validate();
if (form.valid()) {
// Proceed with submit!
}
else {
// Stop submit!
return false;
}
});

Call asp method from c# code behind

On a web application, I need to do some conditional logic and then based on that, possibly show a dialog box. Here's what I need to do:
Button pressed, submitting two IP Addresses
Check if these addresses are 'in use'
If they are:
display confirm box
If "OK" is pressed, call C# function
Otherwise, done
If they're not:
Call C# function
When the button is pressed, it calls the clicked method btnLinkConnect_Click() in the C# codebehind. This then checks for addresses 'in use'. Stepping through with the debugger, this all works fine, but if addresses are 'in use', a javascript script is supposed to run to display the box:
<script type="text/javascript">
function askForOverride(station1, station2) {
var answer = confirm("Station(s):" + PageMethods.GetActiveStations(station1, station2) + "is/are in use. Override?");
if (answer) {
PageMethods.uponOverride(station1, station2);
}
}
</script>
But how can I get this script to run from the C# page? I've looked at ClientScript.RegisterStartupScript(), but I couldn't get it to work, and it appears not to be able to work inside the conditionals. I've looked at ajax, but I couldn't understand exactly how to call it from the C# codebehind.
What is the best way to call this script, or obtain the same result, and how should I go about it?
This may work, add some client events for button click based on condition. Please refactor if necessary
protected void btnSumbit_Click(object sender, EventArgs e)
{
//call some function to verify IP entered by user
bool isExistingIp = VerifyIp(txtIP.Text);
if (isExistingIp)
{
// event argument PASSED when user confirm to override from client side
string isoverride = Request.Form["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(isoverride))
{
//register script if user hasn't confirmed yet
this.ClientScript.RegisterStartupScript(this.GetType(), "displaywarning", "displaywarning();", true);
Page.GetPostBackEventReference(btnSumbit);
}
else
{
//continue with functionality
}
}
else
{
//continue with functionality
}
}
On client side add javascript to display warning and do a post back
function displaywarning() {
var isOverride = window.confirm("do you want to override");
if (isOverride) {
__doPostBack('<%=btnSumbit.ClientID%>', 'override');
}
}
You can easily do this with jQuery AJAX calls.
ASPX
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('body').on('click', '.performsMyClickAction', function () {
$.ajax({
type: "POST",
url: "BlogPost.aspx/TestIP",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d = 1) //In use
{
$("<div>State your confirm message here.</div>").dialog({
resizable: false,
height: 210,
modal: true,
buttons: {
"Ok": function () {
__doPostBack('<%= upnl.ClientID %>', 'InUse ');
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
} else {
__doPostBack('<%= upnl.ClientID %>', 'NotInUse ');
}
}
});
});
});
</script>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="upnl_Load">
<ContentTemplate>
<div>
<asp:Button CssClass="performsMyClickAction" Text="Test IP" ID="Button3" runat="server" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
C#
protected void upnl_Load(object sender, EventArgs e)
{
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
if (string.IsNullOrEmpty(eventTarget)) return;
var arg = Request.Params.Get("__EVENTARGUMENT");
if (arg == null) return;
if (!string.IsNullOrEmpty(arg.ToString()))
{
if (arg.ToString().IndexOf("InUse") > -1)
{
//Call C# function for in use.
}
if (arg.ToString().IndexOf("NotInUse") > -1)
{
//Call C# function for not in use.
}
}
}
[WebMethod]
public static string TestIP()
{
//Check for IP status
if (true)
return "1";
//else
//return "0";
}
Hope this will help you.
Have a look at ClientScriptManager.RegisterStartupScript, i think this should work

Link button will not work with JQuery modal form

I have a JQuery modal form with 4 image buttons. When the modal box opens and I click on those buttons then nothing happens. I know that when the box opens it moves outside of the form but I do not know how to get it back. I have tried several variations on the .parent().appendTo($("form")); and have changed that in many different ways with no success. Currently when I use that the box opens up but the entire screen is darkened and I cannot click on the buttons. Here is my JQuery function:
<script type="text/javascript">
$(function () {
$("#Change").dialog({
resizable: false,
draggable: false,
width: 800,
modal: true,
show: { effect: 'fadeIn', duration: 500 },
hide: { effect: 'fadeOut', duration: 300 },
autoOpen: false,
open: function (type, data) {
$(this).parent().appendTo($("form"));
}
});
$("#ui-dialog-title-dialog").hide();
$(".ui-dialog-titlebar").removeClass('ui-widget-header');
$("#openChange1").click(function () {
$("#<%=txtCardChange.ClientID %>").val("1");
$("#Change").dialog("open");
$('.ui-widget-overlay').live("click", function () {
$("#Change").dialog("close");
});
return false;
});
});
</script>
If needed here is my html to call the modal form:
<a id="openChange1" href="#" style="color: Red">Change Card</a>
The html for the modal form is just inside a simple div tag:
<div id="Change">
\\html here
</div>
So, any help would be greatly appreciated. If needed I am using Visual Studio 2012 with .NET 4.0. The code behind the buttons are in C#. Thank you for your time.
I had the same problem I solved as below:
<script type="text/javascript">
$(function () {
$("#Change").dialog({
resizable: false,
draggable: false,
width: 800,
modal: true,
show: { effect: 'fadeIn', duration: 500 },
hide: { effect: 'fadeOut', duration: 300 },
autoOpen: false,
appendTo: "form"
});
$("#ui-dialog-title-dialog").hide();
$(".ui-dialog-titlebar").removeClass('ui-widget-header');
$("#openChange1").click(function () {
$("#<%=txtCardChange.ClientID %>").val("1");
$("#Change").dialog("open");
$('.ui-widget-overlay').live("click", function () {
$("#Change").dialog("close");
});
return false;
});
});
</script>
In jQuery UI v1.10 they added an appendTo property, which seems to do the same thing as calling .parent().appendTo($("form")). The dialog appears on top of the grayed background. And Post back does work.
As you mentioned, JQuery moves the contents of the dialog to a direct child of the page body to solve several rendering issues: http://forum.jquery.com/topic/preventing-dialog-from-rearranging-dom-flow
The problem is that if you move the buttons immediately back, the 'overlay' div that is used to darken the rest of the screen and make the dialog modal (ie eat click events) prevents your button clicks from happening in the original location.
One solution is to use a clone of your Change div for the modal and bind click handlers that call click() on the original buttons.
Another option is to have the buttons call .NET's postback methods instead of letting the normal HTML form do the submit:
__doPostBack("ctl00$button_name_here");
<asp:LinkButton runat="server" id="openChange1" onclientclick="openChange1Click()" />
<script type="text/javascript">
function openChange1Click () {
$("#<%=txtCardChange.ClientID %>").val("1");
$("#Change").dialog("open");
$('.ui-widget-overlay').live("click", function () {
$("#Change").dialog("close");
});
return false;
}
</script>
Got it, thanks for the help, it steered me in the right direction.
$(function () {
$("#Change").dialog({
resizable: false,
draggable: false,
width: 400,
modal: true,
show: { effect: 'fadeIn', duration: 500 },
hide: { effect: 'fadeOut', duration: 500 },
autoOpen: false,
open: function (type, data) {
$(this).parent().appendTo("form:first");
}
}).parent().css('z-index', '1005');
$("#ui-dialog-title-dialog").hide();
$(".ui-dialog-titlebar").removeClass('ui-widget-header');
$("#Change").hide().show();
$("#openChange1").click(function () {
$("#<%=txtCardChange.ClientID %>").val("1");
$("#Change").dialog("open");
$('.ui-widget-overlay').live("click", function () {
$("#Change").dialog("close");
});
return false;
});
});

jQuery Confirm Replacement In A Simple Situation [duplicate]

Following up from this question, I'm trying to implement an unobtrusive confirm dialog.
$(document).ready(function () {
$("[data-confirmPrompt]").click(function (event) {
var confirmPrompt = event.currentTarget.attributes['data-confirmPrompt'].value;
event.preventDefault();
$.prompt(confirmPrompt, {
buttons: { Yes: true, No: false },
callback: function (v, m, f) {
if (v) {
// User clicked Yes. Unbind handler to avoid
// recursion, then click the target element again
$(event.currentTarget).unbind('click');
event.currentTarget.click();
}
}
});
});
});
When the user has clicked on "Yes", I want the default action associated with the event to execute. I've done it above by unbinding the jQuery handler, and clicking the element again. This works fine when submitting a form or navigating to a different page - but of course does not work in AJAX-enabled pages, where I want to keep the jQuery event handler.
Is there an alternative generic way to execute the default action? Logically something like event.executeDefault().
Using the suggestion Alexey Lebedev made in his second comment, my current implementation now looks like the sample below, except that I've also added my own implementation of localization for the button labels.
Notes:
I'm now using a jqueryUI dialog widget
Note the use of .delegate so that the handler is "ajax-aware", i.e. works on elements added to the DOM after the page is loaded, e.g. as a result of an AJAX call
Uses a flag to prevent recursion when the user clicks Yes on the confirm dialog.
Uses jquery 1.6.4 and jquery-ui-1.8.16
If anyone can suggest improvements, please chime in.
<!-- Examples of usage -->
<input type='submit' data-confirm="OK to delete customer 123?" ... />
<a href="..." data-confirm="OK to navigate?" ... />
<!-- Implementation -->
<script type="text/javascript">
var confirmClickHandler = function (event) {
if ($(event.currentTarget).data('isConfirming')) return;
var message = event.currentTarget.attributes['data-confirm'].value;
event.preventDefault();
$('<div></div>')
.html(message)
.dialog({
title: "Confirm",
buttons: {
"Yes": function () {
$(this).dialog("close");
$(event.currentTarget).data('isConfirming', true);
event.currentTarget.click();
$(event.currentTarget).data('isConfirming', null);
},
"No": function () {
$(this).dialog("close");
}
},
modal: true,
resizable: false,
closeOnEscape: true
});
};
$(document).ready(function () {
$("body").delegate("[data-confirm]", "click", confirmClickHandler);
});
</script>
I'm doing something similar and this works fine for me:
$('#link').click(function(e){
if(!confirm('Are you sure you want to asdf?')){
e.preventDefault();
}
});
I honestly don't know if this answers your question, but it might help a bit.
Consider the following HTML:
<button onclick="alert('Hello world!');" class="btn">Test 1</button>
<button onclick="alert(this.className);" class="btn">Test 2</button>
I've added the following to my $(document).ready:
$('button').each(function() {
var btn = $(this);
var onClick = btn.attr('onclick');
//replace this with _this
onClick = onClick.replace(/this/g, "_this");
btn.attr('onclick', '');
btn.click(function() {
if (confirm('Do it?')) {
//set _this first!
var _this = btn[0];
eval(onClick);
}
});
});
It seems to get the job done. Check this jsFiddle example: http://jsfiddle.net/KeesCBakker/4jThg/.
EDIT
I've created something that looks more like your question: http://jsfiddle.net/KeesCBakker/hqLH5/. Just couldn't figure out which $.prompt plugin your were using, so I grabbed the first one I've found from github (this one only works in Chrome :S).
I was able to achieve this by calling event.stopPropagation() from a more specific context, and ensuring that I don't call event.preventDefault(). While you can't call the default action explicitly, you can set up the conditions so that the default action happens — and do as little or as much else as you wish.
// Normal event handler
$("[data-toggle]").click(ev => {
switchToTab(ev.currentTarget)
ev.preventDefault()
})
// Allow default handler in a specific case.
$("[data-toggle] ul a").click(ev => {
// Don't bubble the event to the less specific handler, above
ev.stopPropagation()
// An incorrect return value will also cancel the default action.
return true
})

Using fb-login-button div class and JQuery

I have a FB login button and want to bind it to a function but I can't seem to get it work:
<div class="fb-login-button" id="auth-loginlink"></div>
This is the line that I am trying to bind it to my fb-login-button
$("#auth-loginlink").click(function () { grantPermission(); });
<script type="text/javascript">
function grantPermission() {
window.FB.login(function (response) {
// ... login stuffs
}
</script>
It will work if I use a normal hyper link like:
Login
Please kindly advice what am I doing wrong. Thanks.
If it's really a button might as well use the button tag:
<button class="fb-login-button" id="auth-loginlink">Login</button>
Put your javascript inside the script tag, and return false in the handler:
<script type="text/javascript">
$("#auth-loginlink").click(function () { grantPermission(); return false; });
function grantPermission() {
window.FB.login(function (response) {
// ... login stuffs
}
</script>
... also might be a good idea to do $("#auth-loginlink").button() but not totally necessary.
Note: If your html is actually below your javascript code the above will not always work.

Categories

Resources