jquery with check box in asp.net adding click event - asp.net

I have textbox and checkbox in asp.net page.
if the check box checked should have an input mask and if its uncheck should have another input mask. my code is always picking up second condition and I've been advised that I should add click event to run the code whenever the checkbox is clicked and because I'm new with jquery i need help to add click event to my script.
please help.
here is my code:
<%# Page Title="" Language="C#" MasterPageFile="~/Imam.Master" AutoEventWireup="true"
CodeBehind="WebForm4.aspx.cs" Inherits="Imam_Contacts.WebForm4" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput-1.2.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
if ($('#chkhtml:checked').length > 0) {
$("#txthtml").mask("999-99-9999");
} else {
$("#txthtml").mask("99/99/9999");
}
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<input id="chkhtml" type="checkbox" checked="checked" />
</asp:Content>

You have to do
<script src="js/jquery.maskedinput-1.2.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
if ($('#chkhtml:checked')) {
$("#txthtml").mask("999-99-9999");
} else {
$("#txthtml").mask("99/99/9999");
}
});
</script>

This code works for me.
$(document).ready(
function() {
$('#chkhtml').click(
function() {
if ($('#chkhtml:checked').length > 0) {
$("#txthtml").mask("999-99-9999");
} else {
$("#txthtml").mask("99/99/9999");
}
});
});

Related

FancyBox doesn't trigger when using it in UserControl

I have ASP.Net Masterpage design & have to user a Fancybox to show videos as modal, When i show videos on a ContenPage & place all related scripts to FB on that page then it works fine for that page without any issue. But i also need Top 10 Videos to be shown on some page as a user control. What i do is that i create a User Control & put all the related scripts in that user control except the main jQuery which i user in masterpage & download as CDE.
In this case fancybox doesnt trigger.
I am to make it work if i black fancy-box related scripts on all contents page which i dont want to.
I want script to be in userControl
I have placed my sample code for user control & master Page below.
USER CONTROL
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ucMostPopular.ascx.cs" Inherits="ucMostPopular" %>
<script src="<%= Helper.ResolveUrl("~/scripts/fancybox/jquery.fancybox-1.3.4.js") %>" type="text/javascript"></script>
<link href="<%= Helper.ResolveUrl("~/styles/english-jquery.fancybox-1.3.4.css") %>" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//Code to Reinitialize Fancybox script when using update panel START
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) { }
function EndRequest(sender, args) { InitMyFancyBox(); }
$(document).ready(function () {
InitMyFancyBox();
});
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
'padding': 0,
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
//'title': this.title, // we will replace this line
'title': newTitle, //<--- this will do the trick
'width': 680,
'height': 495,
'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type': 'swf',
'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
});
// alert(this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'));
$.ajax({
type: "POST",
url: "UpdateVideoViews.aspx?youtubeVideoID="+this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
});
return false;
});
});
}
</script>
<!-- Videos -->
<div id="Videos" class="tab_text">
<div id="popular-videos-wrapper">
<asp:Repeater ID="rptPopularVideos" runat="server" EnableViewState="False" >
<ItemTemplate>
<div class="popular-article-title">
<asp:Label ID="lblCounter" CssClass="lblCounter" runat="server" Text='<%# Container.ItemIndex + 1 %>' > </asp:Label>
<asp:HyperLink ID="hylnkArticle" CssClass="popular-youtube-links" ToolTip ='<%# Eval("VideoTitle")%>' NavigateUrl='<%# generateVideoURL(Eval("VideoYoutubeID")) %>' runat="server" BorderWidth="0">
<asp:Label ID="lblArticleTitle" Text='<%# getVideoTitle(Eval("VideoTitle"))%>' runat="server" ></asp:Label>
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
<!-- Videos -->
MASTER PAGE
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="SiteMasterPage" %>
<%# Register Src="~/en/UserControls/ucLiquidCarousel.ascx" TagName="ucLiquidCarousel" TagPrefix="uc"%>
<%# Register Src="~/en/UserControls/ucNewsTicker.ascx" TagName="ucTicker" TagPrefix="uc"%>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
<asp:Literal ID="litCtrMetaForSM" runat="server"></asp:Literal>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="shortcut icon" href="http://www.alshindagah.com/favicon.ico">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<link href="../styles/english_css.css" rel="stylesheet" type="text/css" />
<link href="../styles/horizontal-menu-english.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder>
<script type="text/javascript">
.....
//Other scripts
.....
</script>
I am not sure why this is not working i have moved script related to fancy box on masterpage then it worked only for default page & failed on other pages.
I also used ResolveURL(...) that didn't work either
I dont get any error regarding script.
I would appreciate help in this regard so that my fancybox will work by placing all the scripts related to fancybox from usercontrol it self

Why is this leaking memory in ie 8?

edit 2 -
To recreate - (I hope)
Create an empty asp.net project, add a default.aspx, and an about.aspx
use this code for the default.aspx file:
http://pastebin.com/4Ri1BufM
and this for about.aspx
http://pastebin.com/Ni9dZL7c
Build, and run sieve against it. Click the button, then the link. Sieve should now list 1 memory leak.
This simple layout puts a server button inside a panel. If you click it, and then the "Leave" link, sIEve reports 1 memory leak:
http://localhost:2605/Default.aspx (1 reference)
<INPUT value="partial postback" type=submit name=ctl01 >
Aspx source:
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="LeakTestProject._Default" %>
<html>
<head>
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button Text="partial postback" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
<a href="SomeOtherPage.aspx" >leave</a>
</body>
</html>
I've think I've tracked down a memory leak in my application to this source.
Would anyone be able to explain why this is happening, and what to do to fix it?
(Note - there is no server side code running)
edit-
Here is the generated html:
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="Default.aspx" id="Form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTUzNzM3OTMxMmRk27mKixZYS2MtHiuw7SZF6+1A/CkWRnnarcN2a05yCJs=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['Form1'];
if (!theForm) {
theForm = document.Form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=_lxNoU5aYdEC_WWnUhGTN0VgFQnwFJ1fkZBkPhUGNITY1Tt87f4CGSPd9dhq2TD9I8lv5ljTGi956KpbHSLq3ebld0t7nKLON7Hc04CCAwA1&t=634525784292792916" type="text/javascript"></script>
<script src="/ScriptResource.axd?d=0VE3fsyoY2cTFnat6m0YjE4OCCjVV0jmjSC6wigMBEOHyKW8kewBrhtJnBFIn73VSWcGW45QXwelC5m-1iZoornC8qWpZ-kXP-Y38e49qW1TbssOgo419ZWtVHSVmIpSg9CvXOQzUBClAjuHORyX5Q2&t=ffffffffbd2983fc" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/ScriptResource.axd?d=DBlWOXkmp0ycsSicGEZhACmLuhW1VF8BppK-Uj8ijyjhFxx7MTG8NW0gLl3IJ6TyEo2rAMfLCQ9rO_bk2wDCcpyT3Df6CN-TLMAA575gUNAjTSzC6U1koagV2FYRmu4TNsAgoEjhkN6fJX3lENf7Bw2&t=ffffffffbd2983fc" type="text/javascript"></script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgLZvOXNBgKiwImNCx8fSMXEwq+V+5yrnoaTcidPwoJw3ebm6DJQ1D3fVVAL" />
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'Form1', ['tUpdatePanel1','UpdatePanel1'], [], [], 90, '');
//]]>
</script>
<div id="UpdatePanel1">
<input type="submit" name="ctl01" value="partial postback" />
</div>
</form>
<a href="About.aspx" >leave</a>
</body>
</html>
According to http://www.codeproject.com/KB/ajax/jqmemleak.aspx there is a memory leak that sounds a lot like what you are experiencing.
See "Iteration 2 - Memory Leak"
Using a tool called 'SIEve' he states 'You can see that every time I click refresh, it creates a new set of input elements without destroying the previous ones. '
His fix was a JQuery plugin that calls into the Update panel cleanup hooks. You could potentially try this?
(function($) {
$.fn.Disposable = function(cln) {
return this.each(function() {
var el = this;
if (!el.dispose) {
el.dispose = cleanup; // will be called by
// Microsoft for cleanup
$(window).bind("unload", cleanup);
}
function cleanup() {
if (!el)
return;
$(el).unbind();
$(window).unbind("unload", cleanup);
el.dispose = null;
el = null;
};
});
};
})(jQuery);
function add() {
$get('res').value =
parseInt($get('i1').value) + parseInt($get('i2').value);
}
Sys.Application.add_load(function() {
$('.num').change(add).Disposable();
});
could you please try this change:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script>
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(my_init);
function my_init() {
document.getElementById("UpdatePanel1").innerHTML = "";
}
</script>

jQuery Validation in ASP.NET

i have a strange situation may its a easy fix or something i may be missing but here is the question.
i have a asp.net form with master page and my validation works great without any problem but the problems starts when i try to hook my click event to the server side,
here is what i meant:
i have a form with few fields on it and if the form is empty than it should STOP submitting, otherwise allow me to execute the server side script
but its not happening, even my form is in invalid state (i do get error message saying i have to enter the required fileds) but still executing my server side script.
i would like to execute my server side script only if the form is in valid state.
here is my code:
my master page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Validation in ASP.NET Master Page</title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
my content page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
$(document).ready(function() {
$("#aspnetForm").validate({
rules: {
<%=txtName.UniqueID %>: {
minlength: 2,
required: true
},
<%=txtEmail.UniqueID %>: {
required: true,
email:true
}
}, messages: {
<%=txtName.UniqueID %>:{
required: "* Required Field *",
minlength: "* Please enter atleast 2 characters *"
}
}
});
});
</script>
Name: <asp:TextBox ID="txtName" MaxLength="30" runat="server" /><br />
Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSubmit" runat="server" onclick="SubmitTheForm();" Text="Submit" />
</asp:Content>
function SubmitTheForm() {
SaveTheForm();
}
function SaveTheForm() {
debugger;
var request = buildNewContactRequest();
ContactServiceProxy.invoke({ serviceMethod: "PostNewContact",
data: { request: request },
callback: function(response) {
processCompletedContactStore(response);
},
error: function(xhr, errorMsg, thrown) {
postErrorAndUnBlockUI(xhr, errorMsg, thrown);
}
});
return false;
}
i have tried both ways
1)
$(document).ready(function() {
$("#btnSubmit").click(function(event) {
event.preventDefault();
SaveTheForm();
});
});
2)
<asp:Button ID="btnSubmit" runat="server" onclick="SubmitTheForm();
function SubmitTheForm() {
SaveTheForm();
}
you're posting your data without checking if the form is valid or not
I think you have to use something like this
function SubmitTheForm() {
if ($("#aspnetForm").valid()) SaveTheForm();
}
Sorry, I'm giving you bad advice. Forget my previous entry. What is the SubmitTheForm() method? You're using the jQuery validation plug in, so you should just need to attach the validation stuff to the form and all should be right with the world.
I think your button onclick needs to be
return SaveTheForm();
As in:
<asp:Button ID="btnSubmit" runat="server" onclick="return SubmitTheForm();" Text="Submit" />
Do you try to put the jQuery code script in the Head ContentPlaceHolder

asp.net jquery how to use Plugin/Validation with web content

I have a asp.net web content from that have a asp.net textbox and I want to use Plugin/Validation but it is not working with me here is my code:
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="IMAM_APPLICATION.WebForm1" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script src="js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("#<%=TextBox1.ClientID %>", function(value, element) {
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
}, "Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Content>
Well I am unsure what the problem is as this does not tell me much "not working".
Just looking at your code I am trying to see might cause it not to work.
First you don't have the validate method hooked up to any form. I don't think you can run it without hooking it up to a form tag.
// from the validation documentation
$("#commentForm").validate();
Notice how they tie the validate field.
Next
I think your doing your .addMethod wrong
$(document).ready(function() {
$.validator.addMethod("#<%=TextBox1.ClientID %>", function(value, element) {
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
}, "Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.");
});
You have what is above but if you look at the documentation.
addMethod( name, method, [message] )
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
see how the first paramter is "name" not "id". Name is like the name of this new method.
So this addMethod could be called "Test101" that would be the name. Or like in the examle you see they named it "math"
next you would do something like this
$("#commentForm").validate
(
rules:
{
txtBoxIdName:
{
math: true;
}
}
);
So it would me something like this. You would put the textboxId in the validate method of the form and then you call your .addMethod inside that id. In my case I used the .addMethod called "math" and I believe you just set it to "true" to make it required and to run.
I have not tested this so I will try to find some examples that actually run.
Edit
Here is what the master page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
see it does have a form id and when you hook this master page with an aspx page you should have this.
<title>
</title>
<script>try { for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++){ var lastpass_f = document.forms[lastpass_iter]; if(typeof(lastpass_f.lpsubmitorig)=="undefined"){ if (typeof(lastpass_f.submit) == "function") { lastpass_f.lpsubmitorig = lastpass_f.submit; lastpass_f.submit = function(){ var form = this; try { if (document.documentElement && 'createEvent' in document) { var forms = document.getElementsByTagName('form'); for (var i=0 ; i<forms.length ; ++i) if (forms[i]==form) { var element = document.createElement('lpformsubmitdataelement'); element.setAttribute('formnum',i); element.setAttribute('from','submithook'); document.documentElement.appendChild(element); var evt = document.createEvent('Events'); evt.initEvent('lpformsubmit',true,false); element.dispatchEvent(evt); break; } } } catch (e) {} try { form.lpsubmitorig(); } catch (e) {} } } } }} catch (e) {}</script></head><body>
<form name="aspnetForm" method="post" action="Default2.aspx" id="aspnetForm">
<div>
<input name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1MmRkJ6rATKUz8lX/wrHNVcM8o9fwof8=" type="hidden">
</div>
<div>
</div>
</form>
</body></html>
So try that if that will be good enough for hooking it up.

Problem placing ContentPlaceHolder within <script> tags

I have this in an ASP.Net Master Page:
<script language="javascript" type="text/javascript">
<asp:ContentPlaceHolder ID="scriptContentHolder" runat="server"></asp:ContentPlaceHolder>
</script>
But when I try to view the content page in design mode it tells me there is an error in the associated Master page because "scriptContentHolder" does not exist.
<asp:Content ID="scriptContent" ContentPlaceHolderID="scriptContentHolder" runat="server">
g_page = "mnuSurveys";
</asp:Content>
If I change the Master page to this:
<asp:ContentPlaceHolder ID="scriptContentHolder" runat="server"></asp:ContentPlaceHolder>
and the content page to this:
<asp:Content ID="scriptContent" ContentPlaceHolderID="scriptContentHolder" runat="server">
<script language="javascript" type="text/javascript">
g_page = "mnuSurveys";
</script>
</asp:Content>
Then all is cool. Why is this? The page compiles and executes just fine... but as above the designer squawks when placing ContentPlaceHolder controls within tags.
I had the same problem and solved it like that:
<%= "<script type=\"text/javascript\">" %>
jQuery(document).ready(function() {
// On document ready, execute this methods...
<asp:ContentPlaceHolder ID="jQueryOnDocReady" runat="server" />
});
<%= "</script>"%>
According to this MS Connect posting as of May '09, the
VS designer doesn't support controls
within script blocks. Alternately, you
can call
Page.ClientScriptManager.RegistgerClientScriptBlock
from content page
[sic]
So you'll have to use the second/work around method you posted.
this may be a bit off track. But I was having the same issue because i had some generic code i wanted in my Master page, and other more specific only on certain pages, here is my solution:
-In my .Master:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
_gaq.push(['_trackPageview']);
</script>
<asp:ContentPlaceHolder ID="PerPageScript" runat="server">
</asp:ContentPlaceHolder>
-In my .aspx:
<asp:Content ID="Content1" ContentPlaceHolderID="PerPageScript" runat="server">
<script type="text/javascript">
...
</script>
</asp:Content>

Resources