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");
}
Related
Having difficulty figuring out how to print the contents of a Join form in BMC Remedy 9.0. Remedy's docs only explain printing Reports, not Join forms. I would like to either be able to print using Ctrl-P or by an internal Remedy process/action link. My Join form contains mostly character fields. Print preview truncates at the first ~20 px of height, despite a page width: 915 px and height: 1000 px. Does anyone know how I can print forms in the browser?
Figured out how to this - if you place all the content inside a Remedy panel object via the WYSIWYG, then you can add a script in the Web Footer to set the document.body.innerHTML equal to the panel's innerHTML. This little trick organizes the elements in a way that makes the page printable using window.print() or Ctrl-P. Be warned, though, that this innerHTML assignment often corrupts or loses properties like child textarea or input values. So you must scrape for these values and append them back to the page before printing.
<div>
<script>
function myPrint()
{
var idTexts = [];
var textareas = document.querySelectorAll('textarea[id][readonly]');
for(var i = 0; i < textareas.length; i++)
{
idTexts.push(textareas[i].id);
idTexts.push(textareas[i].value);
}
var inputs = document.querySelectorAll('input[id][readonly]');
for(var i = 0; i < inputs.length; i++)
{
idTexts.push(inputs[i].id);
idTexts.push(inputs[i].value);
}
//Assume there is only one panel object, so only one .pnl class on the page
var printContents = document.querySelector('.pnl').innerHTML;
document.body.innerHTML = printContents;
for(var i = 0; i < idTexts.length; i++)
{
if(document.getElementById(idTexts[i]))
{
document.getElementById(idTexts[i]).value = idTexts[i+1];
}
}
window.print();
}
/*On page load, I noticed the click event fired for a visible button
without the user actually needing to click.
Will not work unless the button's visibility is set to true (Remedy is a weird creature).
Used the setTimeout to allow time for the initial page load, as the onload event fired too early.
If you don't want this button to appear on the page when it is printed
overlay a transparent image on the button's display properties.*/
document.querySelector('a[ardbn="btnPrintMe"]').onclick = setTimeout(function(){ myPrint(); }, 500);
</script>
</div>
If you still have problems printing, make sure this btnPrintMe button has at least the correct 6 privileges: 1101/-1101, 1102/-1102, 1103/-1103 and the user you are testing this with has the appropriate privileges as well.
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.
I have on one page a dropdownlist which I would like to use AJAX in order to populate it from a XML file. Is there a way to tell AJAX to run only certain asp.net method without using WebServices? Any other solution is welcome but the only restriction is that it would be made on the server side (and not with js for example)?
thanks!
This is possible through a variety of means - one approach is to use jQuery on the client-side to generate the AJAX request like so (binding to the page ready here, but it could be bound to the SELECT change event):
$(document).ready( function () {
$.get('/target-url.aspx?someparam=somevalue', function(data) {
// process the returned data - dependant on the format - assuming JSON here.
var items = data['items'];
// may wish to clear the contents of the SELECT box.
// spin through and add OPTION elements
for(var i = 0; i < items.length; i++) {
$('#selectid').append('<option>'+items[i]+'</option>');
}
}
}
Where selectid is the ID of the dropdownlist element (use the ClientId if in ASP.NET).
Then you need to write some code in ASP.NET to respond to the AJAX request with your desired logic.
Some useful links:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/append/
See here for an example of using jQuery and ASP.NET with JSON:
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/
I have an ASP.NET user control (.ascx file). In this user control I want to use a .js file.
So I include <script src="file.js" type"text/javascript"></script> on the page.
However, sometimes I use this user control in a webpage where this same script has already been loaded.
How can I add a <script /> declaration that will render on the page only if the page doesn't already contain another <script /> tag for the same script?
As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:
this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
... from your page you just call the ClientScript object directly:
ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)
If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.
There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.
Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues.
You can do one of two things client side...
Check the dom for the script tag corresponding to the javascript file your want to check
Test a variable or function you know has/will be defined within the javascript file for undefined.
Here's a quick JS function which uses JQuery to do what you need:
function requireOnce(url) {
if (!$("script[src='" + url + "']").length) {
$('head').append("<script type='text/javascript' src='" + url + "'></script>");
}
}
use something like the following:
if(typeof myObjectOrFunctionDecalredInThisScript != 'undefined') {
// code goes here
var myObjectOrFunctionDecalredInThisScript = { };
}
This tests if your object or function already exists and thus prevents redeclaration.
var storePath = [];
function include(path){
if(!storePath[path]){
storePath[path]= true;
var e = document.createElement("script");
e.src = path;
e.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
return false;
} }
use this in your main page and call function include with argument javascript file name
As you want to include javascript on one page of your site only.
If you use Asp.net(4.0) then it is very easy.
Just include following code
<script type="text/javascript" scr="filepath and name here"></script>
in ContentPlaceHolder of content page.
#Shimmy I am coming across this after a long while but maybe it might still be useful or at least help other coming from behind. To check if jquery is already loaded do this
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.x.x.min.js"><\/script>')</script>
Don't miss the escape character in the closing script tag in document.write statement.
#mysomic, why did I not think of that. thumbs up
PS: I would have loved to write this right under the line where #Shimmy wrote that jQuery itself is the script he wants to load. But dont know how to write it there. cant see a reply or anything similar link. This may sound dumb but maybe I'm missing something. Pls point it out, anybody?
If you need it from server side, and Page.ClientScript.RegisterClientScriptInclude won't work for you in case script was included by some other way other then Page.ClientScript.RegisterClientScript (for example page.Header.Controls.Add(..), you can use something like this:
static public void AddJsFileToHeadIfNotExists(Page page, string jsRelativePath)
{
foreach (Control ctrl in page.Header.Controls)
{
if (ctrl is HtmlLink htmlLink)
{
if (htmlLink.Href.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is ITextControl textControl
&& (textControl is LiteralControl || textControl is Literal))
{
if (textControl.Text.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is HtmlControl htmlControl)
{
if (htmlControl.Attributes["src"]?.ToUpper()
.Contains(jsRelativePath.ToUpper())) return;
}
}
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", page.ResolveUrl(jsRelativePath));
page.Header.Controls.Add(Include);
}
I'm trying to grab the Web.UI.WebControls.HyperLink object itself via javascript so that I can modify its ImageUrl.
Here I'm setting the hyperlink's NavigateUrl to the my javascript function call:
lnkShowHide.NavigateUrl = String.Format(
"javascript:ShowHideElement('{0}');", lnkShowHide.ClientID
)
Here's my javascript function:
function ShowHideElement(img) {
var ele = document.getElementById(img);
if(ele != null) {
// Not sure if this will change the hyperlink's ImageUrl property???
img.src = 'smallPlus.gif';
}
}
However, if I check the value of 'ele' after calling getElementById it prints "String.Format("javascript:ShowHideElement....." and doesn't actually get the hyperlink object itself.
Any ideas would be greatly appreciated!
Why does document.getElementById() return the value of the hyperlink's href attribute?
It doesn't. But when you “alert(element)”, alert() calls toString() on the element, and HTMLLinkElement.toString() returns the contents of the href attribute, so “alert(link)” spits out the same results as “alert(link.href)”.
(Which is a bit weird and confusing, but that's how JavaScript 1.0 worked so there's not much can be done about it now.)
I check the value of 'ele' after calling getElementById it prints "String.Format("javascript:ShowHideElement....."
That shouldn't happen with the exact example you've given... there's no way the server-side “String.Format...” code should make its way through to the client side unless you accidentally enclosed it in quotes, eg.:
lnkShowHide.NavigateUrl = "String.Format(...)";
Other problems that spring to mind are that the function changes name (ShowHideElement/ShowHideImage), and you appear to be trying to set ‘.src’ on the link element (<a>). Links don't have .src, only images do.
Anyhow, you probably don't want to do a show/hide widget like this. javascript: URLs are always the wrong thing, and your example involves a lot of nested strings inside each other which is always fragile. You could try an ‘unobtrusive scripting’ approach, generating markup like:
<div class="showhide"> blah blah blah </div>
With JavaScript to add the open/close functionality at the client side (so non-JavaScript UAs and search engines will see the whole page without hiding bits). eg.:
function ShowHider(element) {
var img= document.createElement('img');
element.parentNode.insertBefore(img, element);
function toggle() {
var show= element.style.display=='none';
element.style.display= show? 'block' : 'none';
img.src= '/images/showhide/'+(show? 'open' : 'closed')+'.gif';
img.alt= show? '-' : '+';
img.title= 'Click to '+(show? 'close' : 'open');
}
img.onclick= toggle;
toggle();
}
// Apply ShowHider to all divs with className showhide
//
var divs= document.getElementsByTagName('div');
for (var i= divs.length; i-->0;)
if (divs[i].className=='showhide')
ShowHider(divs[i]);