attaching jquery function to a span from asp.net code - asp.net

I am trying to add some jquery to span with a class added to it.
I am using asp.net and trying to use RegisterClientScriptBlock to attach the below code to my element. "cphMain_ed1" is hardcoded in this example however I would normally been passing a parameter here just for the ease of this.
<script language="javascript" type="text/javascript">
$(function () {
$('.closeButton').click(function () {
alert('called ok');
$("cphMain_ed1").slideUp();
});
});
</script>
My c# code looks like this
String csName = string.Format("ButtonClickScript_{0}", this.ID);
Type csType = this.GetType();
////// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
// csText.Append("<script type=\"text/javascript\"> HidePanel('" + this.ID + "')");
csText.Append("<script type=\"text/javascript\">DoIt()");
csText.Append("</script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
What am I doing wrong as the function is not been attached to the span with the class "closeButton"
ANy help would be great!!

If you add a class to that user control container you want to hide, so your result is something like this:
<div class="container">
<span class="closeButton">Close</span>
Other content here
</div>
Then you can do away with IDs and code-behind code altogether, and reduce your jQuery down to this:
$(function() {
$('.closeButton').click(function () {
$(this).closest('.container').slideUp();
});
});
Instead of relying on an ID, it just finds the thing you want to hide in relation to the .closebutton. In this case we're using .closest() to get the nearest element up the tree matching the selector...the class that was added to the container you want to close. There are other functions to find things relatively as well, the tree traversal functions, in case you have other situations where this can save you some code.

Related

Access variablea of javascript in .aspx.vb file

I want to access variables defined in Javascript in.aspx file to .aspx.vb file
How can i access variables in .aspx.vb file?
<script type="text/javascript" language="javascript">
var c=0;
var m=0;
var h=0;
var t;
var timer_is_on=0;
function startTMR()
{
document.getElementById('TimeLable').value=h+":"+m+":"+c;
c=c+1;
if(c==60)
{
c=0;
m=m+1;
if(m==60)
{
m=0;
h=h+1;
}
}
t=setTimeout("startTMR()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
startTMR();
}
}
This is simple javascript I'm using in my .aspx page
now i want to access the variable h m and c in .aspx.vb page how to do that?
You'll need to save that javascript variable into a hidden input, which will post with your form when you do a postback. You'll be able to access the value via:
string value = Request.Form["hiddenName"];
Assuming you declare your hidden input like this:
<input type="hidden" id="hiddenValue" name="hiddenName" />
You can set this value like this with native JavaScript:
document.getElementById("hiddenValue").value = "12";
or with jQuery like this:
$("#hiddenValue").val("12");
If you'd like to make sure this hidden input is automatically saved to the JavaScript variable x before you post back, you could do the following with jQuery
$("#form1").submit(function () {
$("#hiddenValue").val(x);
});
Or this with native JavaScript:
document.getElementById("form1").addEventListener("submit", function () {
document.getElementById("hiddenValue").value = x;
});
If you're not using jQuery, and you opt for this native option, just make sure you put the script at the bottom of the body section; do not put this script in the head, since the dom is not formed yet, and you will get a null error.
And obviously this all assumes your form element looks like this:
<form id="form1" runat="server">
if yours has a different id, then adjust accordingly.

jquery , asp.net

I am trying to use jquery to select a checkbox when another checkbox is selected. This wuld have been easy if the ids of the checkboxes are constant but they can change so I have tried to use classes instead, unfortunately asp.net applies the class name on the span element wrapping the checkbox instead of applying on the checkbox directly, so i need to get the checkbox via the inner element of the parent span
<script type="text/javascript">
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkEL_157').click(function() {
if (this.checked) {
var pl = $('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkPL_313')
pl.attr("checked", true);
}
})
});
</script>
My code, previously working with the checkbox ids, is above, pls help!
You can still match your check boxes even if the class attribute is applied to their parent <span> elements:
$(document).ready(function() {
$(".sourceCheckBoxClass input:checkbox").click(function() {
if (this.checked) { // or $(this).is(":checked")
$(".targetCheckBoxClass input:checkbox").attr("checked", true);
}
});
});
With ASP.NET you can control the ClientId of the form controls. You have the use the Clientid property as I remember.
More info at the MSDN.
<script type="text/javascript">
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkEL_157').click(function() {
if (this.checked) {
var pl = $('#ctl00_ContentPlaceHolder1_Category_ctl00_ProductBusinessLine_chkPL_313 :checkbox')
pl.attr("checked", true);
}
})
});
</script>
Is that what you're looking for ? oh and looks like you're using ids, not classes in your selectors
if you write your javascript code on the page, then you can determine real id dynamically:
$('#<$=chkEL_157.ClientID%>').click(function() {
...
});
or find element by a part of id:
$(':checkbox[id$="_chkEL_157"]').click(function() {
...
});
but in this case you must assure that there is no other element that contains similar id. Otherwise you must specify context where you want to find element, like this:
$(':checkbox[id$="_chkEL_157"]', $("#checkbox-context-element")).click(function() {
...
});

asp.net external JavaScript file doesn't find Control.ClientID

On load I'm both calling a JavaScript setTimeout() function that will hide a .NET Panel control, and hiding it in the code behind on first load. Clicking the save button will set the Panel to visible then reload the page at which point a setTimeout() function is called... so basically you click save, and see a panel with "Details Saved" for three seconds, at which point it disappears.
The problem is the external JavaScript file can't find _pDivAlert.ClientID (I've debugged and it returns null). It only works when the code is in a tag in the .aspx page. Any suggestions as to how I can either pass the client ID to the HideControl() function or find the ClientID from the external JS file?
Here's my code, any suggestions?
<script language="javascript" src="Forms.js" type="text/javascript"></script>
<body onload="ToggleAlert()">
<form id="form1" runat="server">
<script type="text/javascript">
//alert the user that the details were saved
function HideControl() {
var control = document.getElementById('<%=_pDivAlert.ClientID %>');
if(control != null)
control.style.display = 'none';
}
function ToggleAlert() {
setTimeout("HideControl()", 3000);
}
</script>
I've also tried sending the ClientID within the ToggleAlert() call, but that didn't work:
<body onload="ToggleAlert('<%=_pDivAlert.ClientID %>')">
External JS:
function HideControl(_c) {
var control = _c;
if (control != null)
control.style.display = 'none';
}
function ToggleAlert(_c) {
setTimeout("HideControl(_c)", 3000);
}
can you show your markup with the panel and the codebehind where you hide it?
there's a difference between setting the Visible property to false and setting the style display attribute to none- the first will not render the element at all, meaning there isn't anything rendered with the id you're looking for.
edit: it's probably because of the way you're calling HideControl in the timeout- this should be a function instead of a string.
try doing
function ToggleAlert(_c) {
setTimeout(
function () {
HideControl(_c);
}, 3000);
}
just for clarity, when you pass a string to setTimeout, it's evaluated and then run. the code chunk that eval produces will run in a different scope than your ToggleAlert method, and so _c won't be available at that time.
edit: you also need to actually get a reference to the control. you're passing the id string to ToggleAlert, which relays it to HideControl, which is expecting an object not a string.
function HideControl(_c) { // _c is the id of the element
var control = document.getElementById(_c);
if (control != null)
control.style.display = 'none';
}

Register OnMouseOver-Event from CodeBehind?

I wan't to register the OnMouseOver and OnMouseOut-Event for an Image from the Code behind, because I must different if the user is logged in or not.
Any ideas?
You can add an attribute to the object.
e.g.
Image img = new Image();
img.Attributes.Add("onmouseover", "myjavascriptfunction();");
To set the paramater based on the id of the object, using this:
Image img = new Image();
img.Attributes.Add("onmouseover", "myjavascriptfunction(" + img.ClientID + ");");
Using ck's example, you can achieve what you're trying to do using the ClientID property on your server control. Like this:
yourImage.Attributes.Add("onmouseover", "jsfunction(" + yourImage.ClientID + ");");
On solution would be to use a css class and jQuery:
<img id="generatedId" class="myHoverImage" />
javascript:
$("img.myHoverImage").mouseover ( function() {
// you can access the generated id:
alert ( this.id );
// --> your code goes here <-- \\
});

Will this jscript run inside a .ASCX page?

Will this run inside an ASCX file in my ASP.Net project?
I can't seem to get it to work, just wondered if there was some particular thing missing? Do i need to include "runat="server""?
<!--[if lte IE 6]>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementById("GetQuote").getAttribute("ImageUrl");
for (var i = 0; i < images.length; i++) {
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
};
</script>
<![endif]-->
It appears that this JavaScript function is attempting to reference ASP.NET web control properties, which are not accessible from the client side. You can, however, reference the HTML entities that are output to the page by ASP.NET, along with their attributes.
Assuming your JavaScript code is code within the .ascx code, change this line:
var images = document.getElementById("GetQuote").getAttribute("ImageUrl");
To this:
var images = document.getElementById('<%=GetQuote.ClientID%>').getAttribute("src");
What this does is insert the client ID that ASP.NET creates for the GetQuote Image control so that it can be referenced from the client side. It also references the proper attribute of the HTML img element (src) that corresponds to the ImageUrl property of the server side Image control.
EDIT:
I noticed after seeing TheVillageIdiot's response (and reading your code a bit more closely, which I should have done initially) that you are trying to use the images variable as an array. It appears that you may be trying to match several image elements that contain the text "GetQuote" in their IDs (like GetQuote1, GetQuote2, etc.).
Assuming that you need to do this on the client side, and that you are not using a framework like jQuery, try this:
window.onload = function()
{
// get all img elements on the page and load them into an array
var images = document.getElementsByTagName("img");
// iterate through the image array
for (var i = 0; i < images.length; i++)
{
// check that the current image's id contains "GetQuote" (case sensitive)
if (images[i].id.indexOf("GetQuote") >= 0)
{
var image_png_src = images[i].src;
var image_gif_src = image_png_src.replace(".png", ".gif");
images[i].src = image_gif_src;
}
}
};
You don't need a runat="server" because this is code that will run on the client. It should work, but maybe you are having problems because you are referencing IDs on items that are asp.net controls? This would mean that your ID values would not match. If so you could solve this by using control.ClientID redndered into the JavaScript server-side to make them match.
If GetQuote is an aspx element then you need to replace it with <%= GetQuote.ClientID %> and ImageUrl with src like
var images = document.getElementById('<%=GetQuote.ClientID%>')
.getAttribute("src");
Also images should be one string not an array of strings so your loop is also at fault. Try this one instead:
var image = document.getElementById('<%=GetQuote.ClientID%>').
if(images){
var src = image.GetAttribute("src");
image.SetAttribute("src",src.replace(".png", ".gif");
}

Resources