开发者

JavaScript Question dealing with different browsers

开发者 https://www.devze.com 2023-03-30 08:53 出处:网络
The problem that I\'m having is that my code works fine in JavaScript but doesn\'t work correctly in Firefox or safari and wondering why. What I\'m doing is I have a loop 开发者_运维技巧going through

The problem that I'm having is that my code works fine in JavaScript but doesn't work correctly in Firefox or safari and wondering why. What I'm doing is I have a loop 开发者_运维技巧going through each element and depending on the variable inside a text box just want to alert something. Like i said earlier this code works fine in IE. Here is the code below:

Here is an example of text box:

<asp:TextBox ID="txtMac" runat="server" req="yes" errMessage="Mac"/>

for (a = 0; a < theForm.elements.length; a++) {
  if (theForm.elements[a].type == "text" && theForm.elements[a].req == "yes") {
    alert("Made it here")
  }
}


Use getAttribute to read the custom attributes. See http://jsfiddle.net/8EWQr/.

So instead of

(theForm.elements[a].type == "text" && theForm.elements[a].req == "yes")

use

(theForm.elements[a].getAttribute('type') == "text" && theForm.elements[a].getAttribute('req') == "yes")


I don't know asp tags. I assume req is a attribute so this should do what you asked by only alerting if the attributes are equal to your requirments, I use a shortcut array to hold all the found elements by tag name as James said its more crossbrowser.

var a = [];
a = document.getElementsByTagName("input");
for(var i=0; i < a.length; i++){

if (theForm.elements[i].getAttribute('type')== "text" &&     theForm.elements[i].getAttribute('req') == "yes" ){
alert("Made it here wtih" + theForm.elements[i]) 
}
} 


Try using document.getElementsByTagName, as I believe this is supported across all browsers.

var linkList = document.getElementsByTagName("a");


http://jsfiddle.net/aaronfrost/Xra5y/1/ That has your answer.


You should use var theForm = getElementById("theForm") instead of calling theForm directly. Only Chrome and IE adds the elements ids to the javascript global scope.

And you should use getAttribute() to get the value of an attribute because only IE has this shortcut.

Try this example.

0

精彩评论

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