JavaScript - Change The "class" Of An Element Using Javascript
Hi all,
I've messing around with CSS and I would like to change the <body> 'class' when the user selects a hyperlink. To do this I've employed the OnClick method within the hyperlink which calls the function updateBodyClass(). Within upDateBodyClass() I would like to add the string "extraMenu" to the body class. Before selecting the hyperlink the body is: <body id="twoColLayout" class="tools"> I want this to change to: <body id="twoColLayout" class="tools extraMenu"> This is the code I currently have but it doesn't work. Please can someone point me in the right direction. Thankyou in advance for your time. <html> <head> <title>test</title> <meta http-equiv="Content-Script-Type" content="text/javascript"> <script> function updateBodyClass() { document.getElementById("body").className="tools"; document.getElementById("body").className+=" extraMenu" return; } </script> </head> <body id="twoColLayout" class="tools"> <a href="index.php" onClick="updateBodyClass()">Search Bookmarks</a> </body> </html> Similar TutorialsHi guys, I have a JS calculator on my website which is basically a load of radio buttons that the user clicks and as they do so a price is calculated in their view. At the moment - the price box starts with a blank box but is essentially "0". Then, as the user select an option, the price appears and then starts to calculate when more than 1 is pressed. All I want to do is have the price start at "300" instead of a blank box or "0". Then the rest of the options calculate onto that. I have tried a variety of ways to achieve it and seem to be missing something! I am pretty new to JS although do have a basic understanding ..... clearly not enough to do this thou! lol Basically imagine 300 is the initial price. That only gets charged once ... Here's my code .... In the <head> Code: <script type="text/javascript"> function getRBtnName(GrpName) { var sel = document.getElementsByName(GrpName); var fnd = -1; var str = ''; for (var i=0; i<sel.length; i++) { if (sel[i].checked == true) { str = sel[i].value; fnd = i; } } return fnd; // return option index of selection // comment out next line if option index used in line above // return str; } function chkrads(rbGroupName) { var ExPg = [ [0,''], [100,"1 extra page"], [200,"2 extra pages"], [250,"3 extra pages"], [300,"4 extra pages"], [350,"5 extra pages"] ]; var ExEm = [ [0,''], [10,"1 extra email"], [20,"2 extra emails"], [30,"3 extra emails"], [40,"4 extra emails"], [50,"5 extra emails"] ]; var ImgBun = [ [0,''], [10,"3 extra image"], [20,"5 extra images"], [30,"7 extra images"], [40,"10 extra images"] ]; var rbtnGroupNames = ['extrapages','extraemail','imagebundles']; var totalprice = 0; var tmp = ''; var items = []; for (var i=0; i<rbtnGroupNames.length; i++) { tmp = getRBtnName(rbtnGroupNames[i]); if (tmp != -1) { switch (i) { case 0 : totalprice += ExPg[tmp][0]; if (tmp > 0) { items.push(ExPg[tmp][1]); } break; case 1 : totalprice += ExEm[tmp][0]; if (tmp > 0) { items.push(ExEm[tmp][1]); } break; case 2 : totalprice += ImgBun[tmp][0]; if (tmp > 0) { items.push(ImgBun[tmp][1]); } break; } } } document.getElementById('QUOTED_PRICE').value = totalprice; document.getElementById('ITEMS_SELECTED').value = items.join('\n'); document.getElementById('PRICE_IN_VIEW').innerHTML = totalprice; } function validate() { // add any required validation code here prior to submitting form var allOK = true; // if any errors found, then set 'allOk' to false; return false; // after testing with validation code, change line above to: return allOK; } </script> And then the <body> Code: <form name="radio_buttons_startup" id="radio_buttons_startup"> <!--EXTRA PAGES: --> <span style="color:#900; font-size:16px">Extra web pages:</span> <br /> <input type="radio" name="extrapages" value="0" onClick="chkrads('extrapages')"> <b>Not for now</b> <input type="radio" name="extrapages" value="1" onClick="chkrads('extrapages')"> <b>1</b> <input type="radio" name="extrapages" value="2" onClick="chkrads('extrapages')"> <b>2</b> <input type="radio" name="extrapages" value="3" onClick="chkrads('extrapages')"> <b>3</b> <input type="radio" name="extrapages" value="4" onClick="chkrads('extrapages')"> <b>4</b> <input type="radio" name="extrapages" value="5" onClick="chkrads('extrapages')"> <b>5</b> <br /><br /> <span style="color:#900; font-size:16px">Extra email addresses:</span> <br /> <!-- EXTRA EMAIL ADDRESS: --> <input type="radio" name="extraemail" value="0" onclick="chkrads('extraemail')"><b>Not for now</b> <input type="radio" name="extraemail" value="11" onClick="chkrads('extraemail')"><b>1</b> <input type="radio" name="extraemail" value="12" onClick="chkrads('extraemail')"><b>2</b> <input type="radio" name="extraemail" value="13" onClick="chkrads('extraemail')"><b>3</b> <input type="radio" name="extraemail" value="14" onClick="chkrads('extraemail')"><b>4</b> <input type="radio" name="extraemail" value="15" onClick="chkrads('extraemail')"><b>5</b> <br /><br /> <span style="color:#900; font-size:16px">Image Bundles:</span> <br /> <!--Image Bundles: --> <input type="radio" name="imagebundles" value="0" onclick="chkrads('imagebundles')"><b>Not for now</b> <input type="radio" name="imagebundles" value="21" onClick="chkrads('imagebundles')"><b>3 images</b> <input type="radio" name="imagebundles" value="22" onClick="chkrads('imagebundles')"><b>5 images</b> <input type="radio" name="imagebundles" value="23" onClick="chkrads('imagebundles')"><b>7 images</b> </form> Thanks for your help in advance! I am trying to manipulate a an image gallery that functions well. Now, I have the ability to pull information from a user's preference pannel and need to place it in the an href="" // And other information in each of the "src" | "url" | "alt". Any ideas would be truly helpful. This is what I am working with at the moment and it doesn't work (obviously because it is adding code inside a span). Here is what I am starting from: [CODE] var title01Span = document.getElementById('title01Span'), //Finds the id that I want prefs = new gadgets.Prefs(), // Pulls from the user's preferences yourtitle01 = prefs.getString("title01"); // Pulls the correct string from those preferences title01Span.innerHTML = yourtitle01; // replaces the span.id with that text but I need to be able to do this in the src / href / url / etc. [CODE] Thank you so much! I seriously could use as much help as possible! I wrote a log function that took note of various function calls. Thinking that functions are first class objects, and objects have properties, I made the name of each logged function a property of that function, e.g., brightenInnerPara.name = "brightenInnerPara"; Every browser I tried (Firefox, MSIE, Opera, Chrome, Safari) accepted the assignment, no problem. In Firefox and MSIE, the result was what I wanted: brightenInnerPara.name == "brightenInnerPara" But in the others, the result was: brightenInnerPara.name == null Question 1. Which Javascript is correct here? I favor Firefox and MSIE, not merely because they were willing to give me what I wanted, but also because it makes no sense to accept an assignment statement without throwing an error and then give it a null semantics, like Chrome, Opera, and Safari did. I found a workaround, using assignments like this: brightenInnerPara.prototype.name = "brightenInnerPara"; To my surprise, that worked in every browser. But I don't know why. It seems that such assignments are enough to cause each function to have its own distinct prototype. Question 2. Just how inefficient is my workaround, and why does it work? Code: for(i=0;i<document.getElementsByName('checkresult_".$i."').length;++i){ if(document.getElementsByName('checkresult_".$i."')[i].checked){ thisurlext+=document.getElementsByName('checkresult_".$i."')[i].value; checkedlength++; if(i+1<document.getElementsByName('checkresult_".$i."').length){ if(document.getElementsByName('checkresult_".$i."')[i+1].checked){ thisurlext+='+'; } } } }; Let's say I check verses 1, 2, 3, 6 I want the Javascript not to ignore the + between the 3 and the 6: Code: <div id="txt_kjv0_1_1_0" style="float: left; background-color: rgb(234, 232, 200); margin: 0px; width: 178px; height: 497px; border: 1px solid rgb(122, 16, 16); padding: 5px 5px 0px; overflow-y: auto; overflow-x: hidden;"> <input id="sc0" value="kjv" type="hidden"> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_0" name="checkresult_0" onclick="" value="1" type="checkbox"><span style="font-weight: bold; margin: 2px;">1</span>In the beginning God created the heaven and the earth.</p> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_1" name="checkresult_0" onclick="" value="2" type="checkbox"><span style="font-weight: bold; margin: 2px;">2</span>And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters.</p> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_2" name="checkresult_0" onclick="" value="3" type="checkbox"><span style="font-weight: bold; margin: 2px;">3</span>And God said, Let there be light: and there was light.</p> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_3" name="checkresult_0" onclick="" value="4" type="checkbox"><span style="font-weight: bold; margin: 2px;">4</span>And God saw the light, that it was good: and God divided the light from the darkness.</p> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_4" name="checkresult_0" onclick="" value="5" type="checkbox"><span style="font-weight: bold; margin: 2px;">5</span>And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day.</p> <p id="regular[]" name="bibletext" style="float: left; text-align: left; width: 155px; display: block; padding: 0px 2px; font-size: 12px;"><input id="check0_5" name="checkresult_0" onclick="" value="6" type="checkbox"><span style="font-weight: bold; margin: 2px;">6</span>And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters.</p> I was under the impression that you can always access any element on a webpage very easily by assigning a value to the "id" attribute. It seems this is true in the Chrome browser but not in the Opera Browser. My God I can't believe how much disarray the state of programming is in when it comes to certain things working in certain browsers...What's the HTML5 standard on this situation...in other words what does the ECMAScript standard say is the proper implementation? Code: <!DOCTYPE html> <html> <head> <title>Project 9-4</title> <script type="text/javascript"> /* <![CDATA[ */ function submitReservation() { var expirationDate = new Date(); expirationDate.setDate( expirationDate.getDate() + 1); document.cookie = "userFirstName=" + inputFirstName.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "userLastName=" + inputLastName.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "userStreet=" + inputStreet.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "userCity=" + inputCity.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "userState=" + inputState.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "pickupDate=" + inputPickupDate.value + "; expires=" + expirationDate.toUTCString(); document.cookie = "returnDate=" + inputReturnDate.value + "; expires=" + expirationDate.toUTCString(); } function displayReservation() { if(!document.cookie) { window.alert("You don't have a reservation!"); return; } var allInputs = document.getElementsByTagName("input"); var crumbs = document.cookie.split("; "); var reservationInfo = "Reservation details: "; for(var i=0; i<crumbs.length; i++) if(allInputs[i].type=='text') { allInputs[i].value = crumbs[i].substring(crumbs[i].indexOf("=")+1, crumbs[i].length); reservationInfo += allInputs[i].value + ", "; } window.alert(reservationInfo); } /* ]]> */ </script> </head> <body> <h1>Hertz Rent-A-Car</h1> <form action="" method="get"> First name: <input type="text" id="inputFirstName" size="16" maxlength="32" /> Last name: <input type="text" id="inputLastName" size="16" maxlength="32" /> <fieldset> <legend>Address<legend> Street : <input type="text" id="inputStreet" size="16" maxlength="32" /> City: <input type="text" id="inputCity" size="16" maxlength="32" /> State: <input type="text" id="inputState" size="16" maxstring="32" /> </fieldset> Pickup date: <input type="date" id="inputPickupDate" name="inputPickupDate" /> Return date: <input type="date" id="inputReturnDate" /> <input type="button" id="buttonSubmit" value="Submit Reservation" onclick="submitReservation();" /> <input type="button" id="buttonDisplay" value="Show Reservation" onclick="displayReservation();" /> </form> </body> </html> Should you be able to access any webpage element by simply specifying the value of it's 'id' attribute? Chrome says 'yes'. Opera says 'no can do'. I get a 'Uncaught Exception;ReferenceError:Undefined variable' error message in the Opera debugger window. The exact same .html document throws no exceptions in the Chrome(version 18) browser. Hey guys, This is my first time ever posting in a programming forum so please be nice! :) I'll admit right away that this is for a homework assignment, but I really did try to solve it myself before I decided to post here. The instructions are to have a confirm box pop up when links with the HTML class value "external" are clicked. If the user clicks "OK" they should be directed to the linked page. If they click "Cancel" they should not be directed anywhere. Here's my code: Code: function checkClass() { var links = document.getElementsByTagName("a"); for ( var i = 0 ; i < links.length ; i++ ) { var link = links[i]; if (link.className == "external") { link.onclick = clickHandler(); } } } window.onload = checkClass; function clickHandler() { if (confirm("You clicked an external link. Do you really want to leave this site?")) { return true; } return false; } The problem is that the confirm box is triggered on page load and not on link click. I know I wrote Code: window.onload = checkClass; but how else should I call the function? I thought Code: if (link.className == "external") would keep it from going as far as to the confirm box until an external link was clicked. Thanks for pointing me in the right direction, Johanna var newlink = document.createElement("a"); newlink.setAttribute("class", "mhs uiButton"); newlink.setAttribute("role", "button"); newlink.setAttribute("href", "http://www.facebook.com/#"); newlink.setAttribute("onlick","FriendBrowserCheckboxController.makeFriendRequest(this, '+javaedit.text+'); return false;"); alert(newlink.classname); why alert newlink.classname return as undefined ? i have set class = mhs uiButton already,should be return mhs uiButton? hi all, im on a really tight deadline with this and have been strugglign all day. (i know nothing about JS!) here's my code: Code: <script language="Javascript"> var allHTMLTags = new Array(); function fadeIn(SRC) { var allHTMLTags=document.getElementsByTagName("*"); for (i=0; i<allHTMLTags.length; i++) { if (allHTMLTags[i].className.indexOf(",") !== -1) { allHTMLTags[i].style.opacity='1'; } } } function fadeOut(SRC) { var allHTMLTags=document.getElementsByTagName("*"); for (i=0; i<allHTMLTags.length; i++) { if (allHTMLTags[i].className.indexOf(",") !== -1) { allHTMLTags[i].style.opacity='0.5'; } } } </script> <li onMouseover="fadeIn(foo)" onmouseout="fadeOut(foo)"> <div class="foo" style="opacity: 0.5;"> test 1 </div> <div class="foo bar" style="opacity: 0.5;"> test 2 </div> The idea of the above, is that when you hover over the <li> all of the divs with a class CONTAINING "foo" are given an opacity of 1. the problem is, the above script only seems to work with numbers?! E.G - class="1 2" works fine. problem is i need to use words not numbers for the classes. clearly my code is rubbish, i've bodged it together from bits and pieces of different forums. PLEASE can somebody help? the end result needs to go through and find all divs with a class CONTAINING the term specified in the <li> then give them an opacity of 1, then on mouseOut return the opacity to 0.5 im sure this is newb stuff, but thanks in advance for any help you can give! Quote: <html> <head> <script type="text/javascript"> var a = january var b = febuary var c = march function test() { document.getElementById("test").innerHTML=a; <!-- needs to be A on first function click, b on second, c on third, etc..^^--> } </script> </head> <body> <p id="test"></p> <!-- the <p> should go to next month upon each function --> <input type="button" value="asdf" onclick="test()" /> </body> </html> I tried to explain it pretty well in the comment tags, thanks! I need to change input type="text" to input type="password" via JavaScript Code: <form id="login" action="#" method="post"> <input id="username-field" type="text" name="username" title="Username" onmousedown="javascript:this.value=''; javascript:this.focus();" value="Username" tabindex="1" /> <input id="password-field" type="text" name="password" title="Password" onmousedown="javascript:this.value=''; javascript:this.type='password'; javascript:this.focus();" value="Password" tabindex="2" /> <input type="submit" name="submit" value="sign in" tabindex="3" /> </form> This works in Firefox and Safari but not IE So then I tried this code Code: <script type="text/javascript"> function passit(ip){ var np=ip.cloneNode(true); np.type='password'; if(np.value!=ip.value) np.value=ip.value; ip.parentNode.replaceChild(np,ip); } </script> <form id="login" action="#" method="post"> <input id="username-field" type="text" name="username" title="Username" onmousedown="javascript:this.value=''; javascript:this.focus();" value="Username" tabindex="1" /> <input id="password-field" type="text" name="password" title="Password" onmousedown="javascript:this.value=''; passit(this.form[0]); javascript:this.focus();" value="Password" tabindex="2" /> <input type="submit" name="submit" value="sign in" tabindex="3" /> </form> This does what I need but turns the username type to password field not the password box Please can somone help! this is not the first time i have run into a situation that has caused me to go "i wish there was some 'onload' event for this div#products so i can execute renderProducts() without waiting for the page to load completely" i dont want to wait for the DOMContentLoaded event, because that causes an annoying restyling of whatever modifications are made by script after the parent containers have already been rendered. it seems like there is no good solution to this so i decided to resort to using inline scripts. eg: Code: <div id="products"> <div id="product_tpl" class="tmplt" style="display:none;"> <h3>{product.name}</h3> <img src="/images/{product.sku}_main.jpg" /><br /> <p>{product.name}</p> </div> <script type="text/javascript">renderProducts()</script> </div> renderProducts() uses an existing javascript object array and fills the div with products using the product template. this way the content is filled and rendered instantly, using the same js function-call that will fill that div for AJAX actions like pagination, filtering, etc. i'm not sure of a better way to do it without having to physically write backend code to replicate the rendering logic. i know that i can just return html from the server for this and ajax calls, but this way i just return data from the server in JSON and let the server take care of the business logic only..more of a web-service model. any input would be appreciated. thanks, Leon I have this code in a .js file: <code> function addElement() { addbranch(); } function IfElseActivity(element) { this.element = element var innerBar=document.createElement("DIV") innerBar.className="bar" innerBar.style["width"]=100+"%" innerBar.style["heigth"]=28+"px" //innerBar.innerHTML = "<p>"+item.id+"</p>" innerBar.innerHTML = "<DIV id='"+element.id+"_id' class='idlabel'>"+element.id+"</DIV>" element.appendChild(innerBar) this.group = Quanticks.drag().createSimpleActivity(element, innerBar) this.Branches = new Array() this.Properties = new Array() this.ActWidth = 360 this.BlockWidth = 160 this.noResizeFlag = false this.noBranchResizeFlag = false } IfElseActivity.GetToolboxIcon = function() { return "/images/ifelse.GIF"; } IfElseActivity.prototype = { Initialize : function() { this.header = document.createElement("img") this.header.src = "images/ifelsehead.GIF" this.header.setAttribute("width", "268"); this.header.setAttribute("height", "49"); this.header.onclick = function() {addElement();}; this.element.appendChild(this.header) this.table = document.createElement("table") this.tablebody = document.createElement("tbody") this.tablerow = document.createElement("tr") this.tablebody.appendChild(this.tablerow) this.table.appendChild(this.tablebody) this.element.appendChild(this.table) this.table.setAttribute("border", "0"); this.addBranch() this.addBranch() this.footer = document.createElement("img") this.footer.src = "images/ifelsefoot.GIF" this.footer.setAttribute("width", "268"); this.footer.setAttribute("height", "49"); this.element.appendChild(this.footer) }, addBranch : function() { var cell = document.createElement("td"); var branch=document.createElement("DIV") branch.className="SequenceActivity" var branchConnector=document.createElement("DIV") branchConnector.className="connector" var innerImg=document.createElement("IMG") innerImg.src="images/connector.gif" branchConnector.appendChild(innerImg) connectors[connectors.length] = branchConnector branch.appendChild(branchConnector) cell.appendChild(branch) this.tablerow.appendChild(cell) cell.setAttribute("vAlign","top") branch.onresize=BranchResize branch.name = getNewId("IfElseBranchActivity"); this.Branches[this.Branches.length] = branch return branch; }, </code> This code creates a kind of ifelse figure on a page with two braches. This works. However, when "this.header.onclick" is clicked an extra branche must be added. Obviously my function does not work. Is the a way to get this working? I would really like to use the original addbranch function Hi. I'm trying to figure out a way that, when a user scrolls down the page and hits the footer (#footer), a div's CSS position changes from fixed to absolute. The main reason is because I don't want the div that if fixed to go over the footer - I want it to just stop scrolling with the page and stay put. I'd assume this is done with JavaScript, but I have no idea where to start. If someone could give me a basic code that I can then modify that would be awesome! Thanks! Hello, I run a online gaming website, and I'm having problems with certain websites iframing our games. Actually I'm ok with iframing, as long as they include the banner ad located just beneath our games. But often times unscrupulous webmasters will iframe only the game, preventing us from generating any revenue from the banner ad (and costing us additional bandwidth charges). I'm hoping to find a way to detect the dimensions of the iframe, so that I may dynamically resize the game, in order to include the banner ad within the iframe. Does anybody know how to extract the "height" and "width" attribute values from an <iframe> tag sitting on a different site? Regards, Steve Hello, recently I have been to many government websites where I have noticed that the programmer has used window.open() method in JavaScript to link to different pages instead of using <a> tags! I was just getting curious to know whether it is normal or has it been used due to security concerns(if any, I don't know)? Any comments? Hi all, I'm having a bit of a problem.. I need to disable the submit button on body onload, and i need to re-enable it when "i agree" is checked. the problem is, it wont do this.. it literally stays disabled, even after check mark.. code: Code: <html> <head><title>Metal Detecting</title></head> <body onload="disable()" oncontextmenu="return false;"> <script> function disable(){ if(document.forms.test.agree.checked == false){ document.forms.test.s1.disabled = true; } } function enable(){ if(document.forms.test.agree.checked == true){ document.forms.test.s1.disabled = false; } } function checkCheckBox(f) { if (f.agree.checked == false) { alert('You MUST agree to the terms by checking the box above.'); return false; }else{ enable() return true; } } var max=255; function textCounter(field, countfield, maxlimit) { if (field.value.length > maxlimit){ // if too long...trim it! field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter }else{ countfield.value = maxlimit - field.value.length; } } function submitonce(theform){ //if IE 4+ or NS 6+ if (document.all||document.getElementById){ //screen thru every element in the form, and hunt down "submit" and "reset" for (i=0;i<theform.length;i++){ var tempobj=theform.elements[i] if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset") //disable em tempobj.disabled=true } } } function checkdata(which) { var pass=true; var t1 = document.forms.test; for (i=0;i<which.length;i++) { var tempobj=which.elements[i]; if (tempobj.name.substring(0,8)=="required") { if (((tempobj.type=="text"||tempobj.type=="textarea")&& tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&& tempobj.selectedIndex==0)) { pass=false; break; } } } if (!pass) { shortFieldName=tempobj.name.substring(8,30).toUpperCase(); alert("The "+shortFieldName+" field is a required field."); return false; } else { return true; } } function emailCheck (emailStr) { /* The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD. 1 means check it, 0 means don't. */ var checkTLD=1; /* The following is the list of known TLDs that an e-mail address must end with. */ var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/; /* The following pattern is used to check if the entered e-mail address fits the user@domain format. It also is used to separate the username from the domain. */ var emailPat=/^(.+)@(.+)$/; /* The following string represents the pattern for matching all special characters. We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */ var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; /* The following string represents the range of characters allowed in a username or domainname. It really states which chars aren't allowed.*/ var validChars="\[^\\s" + specialChars + "\]"; /* The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes). E.g. "jiminy cricket"@disney.com is a legal e-mail address. */ var quotedUser="(\"[^\"]*\")"; /* The following pattern applies for domains that are IP addresses, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */ var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; /* The following string represents an atom (basically a series of non-special characters.) */ var atom=validChars + '+'; /* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */ var word="(" + atom + "|" + quotedUser + ")"; // The following pattern describes the structure of the user var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); /* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */ var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); /* Finally, let's start trying to figure out if the supplied address is valid. */ /* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */ var matchArray=emailStr.match(emailPat); if (matchArray==null) { /* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */ alert("Email address seems incorrect (don't forget to add an @ and a . to your email address!)"); return false; } var user=matchArray[1]; var domain=matchArray[2]; // Start by checking that only basic ASCII characters are in the strings (0-127). for (i=0; i<user.length; i++) { if (user.charCodeAt(i)>127) { alert("Ths username contains invalid characters."); return false; } } for (i=0; i<domain.length; i++) { if (domain.charCodeAt(i)>127) { alert("Ths domain name contains invalid characters."); return false; } } // See if "user" is valid if (user.match(userPat)==null) { // user is not valid alert("The username doesn't seem to be valid."); return false; } /* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */ var IPArray=domain.match(ipDomainPat); if (IPArray!=null) { // this is an IP address for (var i=1;i<=4;i++) { if (IPArray[i]>255) { alert("Destination IP address is invalid!"); return false; } } return true; } // Domain is symbolic name. Check if it's valid. var atomPat=new RegExp("^" + atom + "$"); var domArr=domain.split("."); var len=domArr.length; for (i=0;i<len;i++) { if (domArr[i].search(atomPat)==-1) { alert("The domain name does not seem to be valid."); return false; } } /* domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */ if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) { alert("The address must end in a well-known domain or two letter " + "country."); return false; } // Make sure there's a host name preceding the domain. if (len<2) { alert("This address is missing a hostname!"); return false; } // If we've gotten this far, everything's valid! return true; } </script> Please contact us!<br><br> *Please note you can submit the form ONLY once. Any double form submissions will be deleted.<br> <form name="test" id="test" method="POST" onsubmit="return checkdata(this), emailCheck(this.email.value), checkCheckBox(this)" action="send.php"> <div id = "div01" style="width: 100; height: 25;"> Firstname: <input name="requiredfirstname" id="firstname" type="text" /> Lastname: <input name="requiredlastname" id="lastname" type="text" /> Email: <input name="requiredemail" id="email" type="text" /><br /><br /> </div> <H4>Your statement: </H4> <textarea onKeyDown="textCounter(this.form.statement,this.form.counter,max);" onKeyUp="textCounter(this.form.statement,this.form.counter,max);" name="requiredstatement" id="statement" rows="15" cols="40"></textarea><br /> Characters left: <input readonly="readonly" value="255" size=3 maxlength=3 type="text" name="counter" id="counter"><br/><br /> <textarea name="license" cols="40" rows="15" id="license">Blah!</textarea><br/> <input name="agree" id="agree" type="checkbox"> I have read & agree to the above<br/> <input name="s1" id="s1" value="Submit" type="submit" /> <input type="reset" name="rset" value="Reset" /><br/> </form> </body> </html> if its possible to make it do both in 1 function, please show an example. if you have to use 2 functions, then also show me an example. ANY help is GREATLY appreciated! Hi, I'm having some trouble with XBrowser compatibility. I was just wondering if there is an alternative to getAttribute("class") that works in IE8 and its proceeding versions. The code below checks to see if the current tab/div has the hideDiv class, if it doesn't then it finds the position and dimensions of this and adds them to variables. Pre IE9 sets all the values as it should on the first pass but then when it goes through a second and third time to check the other tabs the values are set to zero as the divs have the display:none property in the CSS. Code: if(tabs[l].getAttribute("class") != "hideDiv"){ findPos(tabs[l]); tabWidth = tabs[l].offsetWidth; tabHeight = tabs[l].offsetHeight; } If you would like to see the full code my development area is dev.creativepanda.co.uk - the function called to start it all off is tabChange code for this is at dev.creativepanda.co.uk/js/tabber.js Thanks for any help that you can give. I need to do an input text validation which include opening parenthesis and closing parenthesis, what I need to validate is the opening parenthesis match with closing parenthesis. Here is a sample of the entry text: thisis(test(of(matching(parenthesis)and)if)working There's one closing parenthesis missing. I would like to warn the user to correct it before submit, but not quite sure how to do it with javascript. Please advice. Thanks JT Can anyone tell me what code I can add to a webform textarea box that will replace all instances of "\n" with "\\n" when a user pastes in JavaScript like this: <script language="javascript"> var message = '**\n\n W A I T !\n\n CLICK CANCEL\n TO STAY ON THE CURRENT PAGE.\n\n I HAVE SOMETHING FOR YOU!\n\n**'; var page = 'http://google.com'; </script> <script language="javascript" src="http://siteactor.com/test.js"></script> The form is on a .php page. The form posts via a .cgi script. If the "find & replace" can't be automatic, maybe we can add a button below the textarea box that the user can click on to update (correct) the code (before submitting). I am not a programmer... so any specifics you can give me will be much appreciated. Thank you. i am trying to make a comment editor with iframe, and want to trigger the change of content inside iframe, the following code cant work. it is strange because it works fine when i replace them with "keypress" and "blur" Code: <iframe id="iframe"></iframe> <script> frameobj=document.getElementById('iframe').contentWindow; // IE frameobj.attachEvent('onpropertychange', function(){alert();} ); //FireFox frameobj.addEventListener('input', function(){alert();} , false); </script> |