The following code is throwing two alerts as expected in IE but not in Firefox. Please help.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function myFunction(){
alert('myfunc');
document.getElementById('mylabel').click();
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<p id='mylabel' onclick="alert('you reached');"></p>
<input type='button' value="Click me" onclick='myFunction();'/>
</BODY>
</HTML>
Firefox only has a click() function for form elements such as buttons. However, you can call the onClick function directly; you can change the line to
document.getElementById('mylabel').onclick();
This works in firefox or IE (but note that it requires that the function actually exists, which you know it does in this example).
Also note that you aren't actually simulating a click on that element (so, for example, if there were other things that such a click would do, such as also act as a click on the container, they won't happen). You're just getting the function that would run on a click, and running it directly. So it's not a solution for all situations where you need to simulate a click.
There's no click method on elements. Are you using any library?
Usually you have to do something like element.fireEvent('click') (prototype, mootools)
or element.click() (jquery)
UPDATE- Similar question: How do I programmatically click on an element in JavaScript?
Looks like an ugly and brittle solution, if I were you I'd just include jQuery and let that handle all the browser quirks.
Because the <p> tag does not have the method click.
Related
I'm trying to set up a page that calls an external Javascript function when the user presses a button in an html form. The function name is lock(), and my code for the button is as follows:
<form>
<button type="button" onclick="lock()">Pause/Play</button>
</form>
Trying to run the code gives the following error:
The value of the property 'lock' is null or undefined, not a Function object
I have confirmed that the function I'm trying to call is a global one in the scope of the .js file, and I know that the .js file is being loaded when the page starts because all of the functionality except for this button works. Am I missing any obvious steps and, if not, what do I need to verify? Thanks.
if you open up dev tools, such as f12 in chrome, and enter lock in console, does it return the function? or undefined?
its impossible ot tell whats going on without seeing your code.
a few things you can try:
1.Include the script tag right above the closing tag of the body, to ensure that the script is loaded after the button.
Attach the event handler to the button not inline, but in the domcontentloaded event.
to debug, try calling some other function from same button, to islotate the problem, and vice versa, try attaching the function to a different button, see if it works there.
Where did you have the javascript line in your html that calls the function from other source? If you had that plotted inside <head></head>, then try move the line way further to below in your html file like right before </body> like as for example:
<html>
<head>
<title>My HTML</title>
</head>
<body>
<blah></blah>
<script type="text/javascript" src="myexternal.js"></script>
</body>
</html>
I am working with Iframes for controlling the elements of iframe by automating it from the parent html file.
I was trying to to click the link defined in iframe.html file from the test.html file using function click() on javascript while loading test.html :
Test.html file :
function handleMainOnload(){
alert("main frame loaded");
var innerFrame = document.getElementById("frame1");
alert("hi-1" + innerFrame.ownerDocument.title);
var innerDocument = frame1.document;
alert("hi" + innerDocument.title);
innerDocument.getElementById("input1").value = "Dynamically Inserted Text";
innerDocument.getElementById("a1").click();
}
<body onload="handleMainOnload();">
<iframe id="frame1" src="iframe.html"/>
iframe.html file :
<a id="a1" href="http://www.google.co.in"> Google.. click</a>
This achor id = a1 automatically get clicked onload of test.html in IE but doesn't work on any browser apart from IE. Please help.
From Javascriptkit.com:
click() - Executes a click on a element as if the user manually clicked on it. In most browsers, click() only works on form INPUT elements that's non "submit" or "reset". It can't be used to simulate a click on a link or form submit button.
I have verified that this is the reason why it's not working for you. Also, I had to change the following line:
var innerDocument = frame1.document;
to
var innerDocument = window.frames["frame1"].document;
Will update with a way to do this in jQuery.
EDIT:
Here's how you do it in jQuery. Essentially you bind a click event and then call click() on the element. This simulates the action since there is no standard way of executing clicks on hyperlinks.
$(document).ready(function() {
$("#frame1").ready(function () { //The function below executes once the iframe has finished loading
alert("iframe loaded");
$('#frame1').contents().find('#a1').click(function() {
alert("Hello");
$('#frame1').attr('src', $('#frame1').contents().find('#a1').attr("href"));
$('#frame1').load();
});
$('#frame1').contents().find('#a1').click();
});
});
Create the event, initialize it and dispatch it on the node.
See https://developer.mozilla.org/en/DOM/element.dispatchEvent for example.
Just remember to call createEvent on the document that has the node you're going to dispatch on.
You can do this without jQuery and without click event handlers on the anchor tags. (Confirmed with IE 9, FF 15, Chrome 23)
The reason it wasn't working (and for JackWilson's edit) is that [in IE at least] innerFrame.document == innerFrame.ownerDocument, so you were not actually looking for the anchor in the iFrame's content document. Use innerFrame.contentDocument instead.
(I haven't confirmed JackWilson's solution for using window.frames[] in browsers other than IE but some browsers may require referencing window.frames[] by index instead of its id. Anybody know for sure?)
Main page: "aclicktest.html":
<!DOCTYPE html>
<html>
<head><title>A click test</title></head>
<body onload="clickIframe();">
<a id="alocal" href="http://stackoverflow.com" target=_blank>Local link</a>
<iframe id='frame1' src="iframeaclicktest.html"></iframe>
<input type='button' value='click local' onclick='clickLocal();'/>
<input type='button' value='click iframe' onclick='clickIframe();'/>
<script type="text/javascript">
function clickLocal(){document.getElementById("alocal").click();}
function clickIframe(){document.getElementById("frame1").contentDocument.getElementById("aiframe").click();}
</script>
</body>
</html>
Iframe page: "iframeaclicktest.html":
<!DOCTYPE html>
<html>
<head><title>A click test IFRAME</title></head>
<body>
<a id="aiframe" href="http://stackoverflow.com" target=_blank>IFRAME link</a>
</body>
</html>
That's interesting that your old code was working in IE. What version? And did you define doctype? It may have been quirks mode behavior.
I am trying to attach a click event to a check box using JavaScript. Shown below is the HTML and JS.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<input type="hidden" name="caution_c" value="0">
<input type="checkbox" id="caution_c" name="caution_c" value="1" tabindex="120">
<script type="text/javascript">
var cb = document.getElementById('caution_c');
cb.onclick = function() {
alert(1);
}
</script>
</body>
</html>
The problem is that in IE, the click event does not fire. I have narrowed down the problem location. The issue is that there is a hidden input just before the check box and both these elements have the same name. I'm not sure why this is causing a problem(after all, I'm using getElementById and the hidden element does not even have an id).
Is there a valid reason for this type of behavior (IE only. Works fine in Firefox...as always :( )? Also, is there a good workaround (I could just do document.getElementsByName('caution_c')[1] but I don't want to...)
Internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.
You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2) override IE's native getElementById-method.
Read more about it here.
Try using a different event such as onchange or onfocus to see if that solves it. Also I don't think onclick will be fired if a user tabs onto the checkbox, which may or not be how you intend it to work.
I agree, IE is poor in understanding things at html level.
I would rather add the link to button rather than using anchor elements, as IE is having trouble at anchor level with document.getElementById(). Try same at button and will work for other users.
I'm trying to add a Javascript function to the onLoad event of a asp:Panel. It goes something like this:
string clickFunction = "$('[id*=lblHiddenPageArray]').text('');"
PagesPanel.Attribues.Add("onLoad", clickFunction);
I'm attaching this function to other controls (Checkboxes and Buttons) and it's working fine. But in the PagesPanel (my asp:Panel control) it HTMLEncodes the function. The output source looks like this:
onLoad="$('[id*=lblHiddenPageArray]').text('');
I've tried to Server.HTMLDecode it on the assignment, but I get the same thing. I've run into this before in .net 4.0. Surely there's a way to escape the characters or something?
I think that's proper behavior. The attribute values are unencoded by the browser before being executed. A simple example:
<!DOCTYPE html>
<html>
<head>
<title>foo</title>
</head>
<body onload="alert('foo');">
<p>foo</p>
</body>
</html>
Just in case you for some reason can't un-HTML-encode things in your head ;-), Firebug in Firefox, the WebKit inspector in Safari and Chrome, and Dragonfly in Opera will do it for you automatically.
I'm not sure what I'm doing wrong here:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
eventInit.js
window.onload = function () {
alert("check"); // works
var jsWarning = document.getElementById("javascriptWarning");
jsWarning.onclick = function () {
alert("hi"); // works
};
jsWarning.onload = function () {
alert("loaded"); // fails
};
}
And yet, nothing happens. What am I doing wrong? I've tried other events, like onmouseover and onload.
I'm doing this in Visual Studio, and intellisense isn't giving me options for setting any event handlers. Is that because I'm doing this wrong?
I have confirmed that JS is working on my setup; just putting alert("hi") in a script and including it does work.
It might be important to note that I'm doing this in JScript, since I'm using Visual Studio 2010, so perhaps event handling is different?
Updated to remove '-' from the ID name, but it still doesn't work.
Updated added the window.onload block. Now onclick works, but onload doesn't.
You are trying to set a load event on a paragraph. Only objects which load external data (window, frame, iframe, img, script, etc) have a load event.
Some JS libraries implement an available event (such as YUI) — but you know the paragraph is available, since you're setting an event on it, and you couldn't do that if it was unavailable.
maybe you forgot to have the code block inside a
window.onload = function() {
// btn click code here
}
You have to wait for the document to be parsed before you can go looking for elements by "id" value. Put your event handling setup into an "onload" function on the window object.
The browser won't fire an "onload" event on your <p> tag. You won't need that anyway if you do your work in the "onload" handler for the window as a whole.
[soapbox] Use a framework.
The script is executed before the desired element exists. Additionally, I don't think, p has an onload-Event. Windows, frames and images, yes, but paragraphs?
You should use <body onload="init();"> or window.onload=function(){ … } or a library function, if you use a library. Example:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
scripts/eventInit.js
window.onload=function(){
alert('JS is working!');}
Edit: Okay, I am very sure, p makes no use of an onload event handler. And it's no wonder, you don't need it. If you want to execute JS code just after the paragraph is finished, do this:
<p>
<!-- stuff -->
</p>
<script type="text/javascript">
/* stuff */
</script>
Instead of this:
jsWarning.onload = function () {
alert("loaded"); // fails
};
try this
if(jsWarning) alert("loaded");
I think someone above mentioned checking for the existence of the element. At this stage the element should be present but it does no harms to check for it.
I think you have to make sure your JavaScript is binding.
Is your javascript before or after your paragraph element, for some reason my brain is aiming towards that.
I would look into using something like jQuery, it will help.
using jQuery your code would be (with the relevant jQuery files included of course):
$(document).ready(function()
{
$("#javascript-warning").click(function(){
alert("HELLO");
});
});
I don't think hyphens are valid in class names when used in conjunction with JavaScript. Try an underscore instead.
onload is a window event.