开发者

Javascript working in JSFiddle - Browser says "Undefined"

开发者 https://www.devze.com 2023-04-12 15:34 出处:网络
I posted on here before and received a great answer - however on further use, the code is showing errors in Firebug and not working properly in testing.

I posted on here before and received a great answer - however on further use, the code is showing errors in Firebug and not working properly in testing.

Original question.

JSFiddle solution

Firebug error shows: document.getElementsByName("licenseAgreement")[0] is undefined 开发者_运维百科(line 1)

Any help would be wonderful.


Numerous issues. The most likely main issue is that you are running your code before the page has loaded and thus the licenseAgreement object is not yet valid. Here's a summary of the things you should change.

First, this code won't work in IE before IE9 for several reasons. getElementsByName isn't properly supported in IE and addEventListener isn't supported at all before IE9. You will have to use attachEvent with IE and addEventListener in other browsers. See the jsFiddle below for code to do that.

Second, I'd suggest you change to document.getElementById() and give your targeted elements an id value instead of name value. This will get you the exact element you want and is supported cross browser. See the jsFiddle below for how to use getElementById instead.

Third, you don't show us the actual working page, but my guess would be that you are running your code to attach an eventListener before the page has finished loading which would mean that it can't find the licenseAgreement object because it hasn't yet been parsed and loaded into the page. Just a guess since you haven't shown us the actual page that fails. You can either move your intialization code to the end of the HTML body or you can not call it until after the page has loaded by hooking a page load event and calling it from there. Your jsFiddle may work because you have specified in the jsFiddle that you don't want your code to run until the page has loaded (a jsFiddle feature).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号