JavaScript - Javascript Function Not Working Correctly
Hi,
I wonder if someone can help! I am not a JavaScript programmer at all, so I cant really see what I am doing wrong with the following code... Just to explain I have 2 fields on a form that retrieve monetary data from a mysql database. The data is a monetary value e.g. 12.59. Which works fine as normal. I have been asked to hide this value depending on what the customers preferences are set to i.e Show Price = Yes or Show Price = No. Hopefully that makes sense. After lots of deliberation I realised that I couldnt hide the fields because the database called an error saying the price data was missing. So I thought change the field type to a 'password field' and the price data would still be accepted by the database. This thankfully worked and didnt break the php code. So I found some javascript code, chopped and pasted it and came up with the following script. This is called with an onclick event through a link. <script language="JavaScript"> function changetype(){ var myTextField = document.getElementById('hf_showmobprices'); if(myTextField.value == "Yes") document.getElementById('price1jd').type='password'; document.getElementById('price2jd').type='password'; else return false; } I thought the above would work but it doesn't. If I take out one of the lines "document.getElementById('price2jd').type='password';", then it does work. After more playing around I thought, create a function caller as shown below but again that doesnt work. The first function works but the second function doesnt seem to work. I shoved in an alert just to check that the second function was being called and it is. So what I gather is It seems to convert the first price field to a password type field but not the second field. Does anyone know why? is it some thing to do with the getElement and can only run once? I am using FireFox 3.6 if that will help <script type="text/javascript"> function checkprefs() { price1(); price2(); } </script> <script language="JavaScript"> function price1(){ var myTextField = document.getElementById('hf_showmobprices'); if(myTextField.value == "Yes") document.getElementById('price1jd').type='password'; else return true; } </script> <script language="JavaScript"> function price2(){ var mynewtestField2 = document.getElementById('hf_showmobprices'); if(mynewtestField2.value == "Yes") document.getElementById('price2jd').type='password'; else alert("alert2") } </script> Any guidance would be much appreciated john Similar TutorialsI read that you don't allow homework assignments to be posted, but this is only one small section of the assignment (1 page of 5), and I have a migraine, and I am utterly hopeless and lost (ha)... I was wondering if there was any errors you could point out to me that would explain why the button isn't doing ANYTHING (i.e. not calculating the sum, average, or grade) when i click it. I'm new to js so I'm sure it could be pretty much any n00b error in the function code. But like I said any help would be greatly appreciated... Code: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <link href="5A.css" rel="stylesheet" type="text/css" media="screen"/> <script type="text/javascript"> function DisplayGrades() { var aNum= 1* document.getElementById("txtaNum").value; var bNum= 1* document.getElementById("txtbNum").value; var Avg = (aNum+bNum)/2; document.getElementById("txtAvg").value=Avg; var Sum= aNum+bNum; document.getElementById("txtSum").value=Sum; var alphaGr= document.getElementbyID("txtalphaGr").value=alphaGr; if (Avg <= 60) alphaGr="F"; if (Avg>60 && Avg <= 70) alphaGr="D"; if (Avg>70 && Avg <= 80) alphaGr="C"; if (Avg>80 && Avg <=90) alphaGr="B"; if (Avg>90 && Avg <=100) alphaGr="A";} </script> </head> <body> <div id="wrapper"> <div id="interact"> Enter your grade for Test 1: <input type="text" id=txtaNum" class="controls" size="10" /> <br /> Enter your grade for Test 2: <input type="text" id=txtbNum" class="controls" size="10" /> <br /> <input type="button" id="btnDisplayGrades" value="Display Grades" onclick="DisplayGrades();" /> <hr/> Sum of Your Grades: <input type="text" id="txtSum" class="controls" size="10" readonly="readonly" /> <br/> Average Grade: <input type="text" id="textAvg" class="controls" size="10" readonly="readonly" /> <br /> Alpha Grade: <input type="text" id="txtalphaGr" class="controls" size="10" readonly="readonly" /> </div> </div> </body> </html> Hi There, I have recently completed making a website for my sister's wedding. I am quite new to the web design world, and have only taken 2 classes on the subject. I used a Javascript function that was provided to us in one of my HTML coding classes in order to automatically resize the (nesting?) div's according to how long the content in them is. This all seems to work perfectly fine in Google Chrome, as well as most versions of Internet Explorer - however, in some versions of internet explorer, and ALL versions of Firefox, this resize function does not seem to work. Since this coding was provided to me by a teacher (who is unfortunately in another country), I'm not sure what kinda of edit would make it so it would function in Firefox, or if there is a way to make in function in Firefox at all. I would appreciate if some of you could take a look at it, and let me know if you have any ideas/suggestions/advice, as to what is happening with the code/why it does not work in Firefox/some versions of Internet Explorer. The specific javascript code (which i assume is the issue here - please let me know if I'm wrong about it being the javascript that isn't working) is he PHP Code: function fnReset(){ document.getElementById('dTorso').style.height="380px"; document.getElementById('dMiddle').style.height="auto"; var middleHt=document.getElementById('dMiddle').scrollHeight; var maxHt=Math.max(380,middleHt); document.getElementById('dTorso').style.height=maxHt + "px"; document.getElementById('dMiddle').style.height=maxHt + "px"; } Which is then called to action he Code: <body onLoad="fnReset();> Also, in some versions of Firefox, the background image for the whole page isn't showing up either - any tips on why that is happening would also be amazing. Thank you so much for any help you may provide. This is a gift to my sister and her fiance, and I really want it to work well for them, and all their guests. Thanks! Hey guys, My code works perfectly fine in internet explorer and google chrome, however, in firefox it does not. I have created an online form, but nothing happens when pressing the "submit" button firefox, whereas in other browsers, it works correctly. Also, the centering of the form is different. Please help me if possible. Thanks <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Airduct Cleaning</title> <meta http-equiv="Content-Type" content="text/html; charset=euc-kr"> <link href="text.css" rel="stylesheet" type="text/css"> <script type="text/JavaScript"> function gosubmit(){ musimw.submit(); } </script> <style type="text/css"> #text { width: 250px; position: relative; margin-left: 200px; } </style> </head> <body leftmargin="0" topmargin="0"> <table width="998" heigt="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="147" valign="top"> <!----LEFT MENU---------> <? include "left_menu.php"; ?> </td> <td width="591" valign="top" colspan="1"> <!----TOP---------> <? include "top.php"; ?> <!----TITLE---------> <table width="100%" heigt="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="590" height="33" background="images/top_bg2.gif" valign="bottom"><img src="images/title_sub09_01.gif" /></td> <td width="1" bgcolor="#d3dfe6"></td> </tr> </table> <!----CONTENT---------> <!----story------> <form action=sendmail2.php method=post name=musimw enctype=multipart/form-data onSubmit="return musimm_check(this);"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr style=" position: relative; margin-left: 28px;"> <td width="50"></td> <td><p><span class="stxt2">Call for a Free Estimate</span><br> <br> <img src="images/img25.gif" align="left"><strong>For a free estimate, call: </strong></p> <div id="text"> Office: Insert Office #<br /> Toll-Free: Insert Toll Free # <br /> Email: Insert Email<br /> <br><em>Or, submit the online form below.</em> </div> </td> </tr> <tr> <td width="50"></td> <td> <table width="530" align="center" border="0" cellspacing="0" cellpadding="0" bgcolor="#EFEFEF"> <tr> <td width="10"></td> <td width="180" height="25">*First name</td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='fname'/></td> </tr> <tr> <td width="10"></td> <td width="180" height="25">*Last name</td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='lname'/></td> </tr> <tr> <td></td> <td >Phone Number<br /></td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='ptel'/> <select name='pteltype'> <option value='Home'>Home</option> <option value='Work'>Work</option> </select></td> </tr> <tr> <td></td> <td >Cell Phone Number<br /></td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='ctel'/></td> </select></td> </tr> <tr> <td></td> <td height="25">*Email Address</td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='email'/></td> </tr> <tr> <td></td> </tr> <tr> <td colspan="3"height="1" background="images/point.gif"></td> </tr> <tr> <td width="10"></td> <td width="180" height="25">*Type of Service</td> <td style="padding:10px 5px 5px 5px"><select name='bnametype'> <option value='Air Duct Cleaning'>Air Duct Cleaning</option> <option value='Dryer Vent Cleaning'>Dryer Vent Cleaning</option> <option value='Chimney Cleaning'>Chimney Cleaning</option> </select></td> </tr> <tr> <td></td> <td height="25">Square Footage<br /></td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20" name='feet'/></td> </tr> <tr> <td></td> <td height="25">Approximate # of Ducts<br /></td> <td style="padding:10px 5px 5px 5px"><input type="text" size="20"name='vent' /></td> </tr> <tr> <td></td> <td height="25">Number of furnaces</td> <td style="padding:10px 5px 5px 5px"><select name='furnaces'> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> </select></td> </tr> <tr> <td colspan="3"height="1" background="images/point.gif"></td> </tr> <tr> <td></td> <td valign="top" style="padding-top:5px">*Address</td> <td style="padding:10px 5px 5px 5px"><input type="text" class="inputPlain004" size="30" name='address'></td> <tr> <td></td> <td height="25">*City<br /></td> <td style="padding:10px 5px 5px 5px"><input name="city" type="text" class="inputPlain004" value="" size="12"></td> </tr> <tr> <td></td> <td height="25">*State </td> <td style="padding:10px 5px 5px 5px"><select name='statetype'> <option value='State'>IL</option></td> </tr> <tr> <td></td> <td height="25">*Zip Code</td> <td style="padding:10px 5px 5px 5px"><input name="zip" type="text" class="inputPlain004" value="" size="12"></td> </tr> <tr> <td colspan="3"height="1" background="images/point.gif"></td> </tr> <tr> <td></td> <td valign="top" style="padding-top:5px">Comments or Questions</td> <td style="padding:10px 5px 5px 5px"><textarea name='Comment' cols="45" rows="8"></textarea></td> </tr> <tr> <td colspan="3"height="1" background="images/point.gif"></td> </tr> </table> <!---BUTTON---> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td height="50" align="center"><a href="javascript:gosubmit()"><img src="images/bt_submit.gif"></a> <a href="#"><img src="images/bt_cancel.gif"></a></td> </tr> </table> </form> </td> <td width="1" bgcolor="#d3dfe6"></td> </tr> </table> </td> <td width="260" valign="top"> <!----RIGHT--------> <? include "right_menu.php"; ?> </td> </tr> </table> <!------BOTTOM----------> <? include "foot.php"; ?> </body> </html> hello, i have a form validator that works fine in chrome, safari, firefox...but not IE 8.. i'm pretty new at javascript... any help is appreciated Code: function detect() { if(navigator.cookieEnabled == false) { alert('You must enable cookies in your browser!'); return false; } if(document.add.color.value == "-Select Color-") { alert('Please select a color!'); return false; } if(IsNumeric(document.add.quantity.value) != true) { alert('This must be a number!'); return false; } if(document.add.quantity.value == 0) { alert('You must add at least one item!'); return false; } } and the html Code: <form name='add' onSubmit='return detect();' method='POST' action='process.php'> I have a js replace function to replace text next to two radio buttons on a pre set form. Script is as follows. Code: document.body.innerHTML = document.body.innerHTML.replace( "Payment by <b>Moneybookers</b> e-wallet<br>", "" ); document.body.innerHTML = document.body.innerHTML.replace( "Maestro, Visa and other credit/debit cards by <b>Moneybookers</b>", "Pago con Diners Club, Mastercard o Visa" ); The script works fine in Chrome and Firefox, however, the script is not actioned in Explorer. I believe it has something to do with there being , / - within the text I am replacing? When I use the function to replace text with no , / - in the text - it works fine in explorer, however, for example when I try to replace text.. - "Maestro, Visa and other credit/debit cards by Moneybookers" this does not work in explorer.. I'm assuming because of the coma and forward slash. Honestly I've tried everything but just can not get this to work. I have no access to the HTML table where the form is posted this is why I am attempting this funtion. Any help would be greatly appreciated!! Hey everyone. I have built a simple page for where I work, nothing complex going on here at all. But for some reason it won't run the Javascript functions in Firefox. Sarfari and Chrome work fine. It's not calling any external files or anything, like I said super simple. So if anyone can go to the page, view the source, take a look and let me know what I am missing here I would be greatly appreciative. http://www.aaronhager.com/BM/ To see what it does, just open that link in Chrome or Safari. I am more of a Flash guy then Javascript, and hopefully the reason is simple for one of you geniuses out there. Thanks A. I have an function that shoud be activated when the pull down menu in triggerd, the if functions is corresponding to the same menu overig_eenh[] PHP Code: function overig_tot_abs(selectVeld, nr) { // Prijs totaal if (document.getElementsByName('overig_eenh[]')[nr].value == 'totaal') { document.getElementsByName('overig_totaal[]')[nr].value = (document.getElementsByName('overig_prijs[]')[nr].value).toFixed( 2 ) } // Prijs kg if (document.getElementsByName('overig_eenh[]')[nr].value == 'kg') { document.getElementsByName('overig_totaal[]')[nr].value = (document.getElementsByName('overig_prijs[]')[nr].value * (document.getElementsByName('materiaal_tot_gew[]')[nr].value + document.getElementsByName('plaat_tot_gew[]')[nr].value)).toFixed( 2 ) } // Prijs verf opp. if (document.getElementsByName('overig_eenh[]')[nr].value == 'verf_opp') { document.getElementsByName('overig_totaal[]')[nr].value = (document.getElementsByName('overig_prijs[]')[nr].value * (document.getElementsByName('materiaal_tot_verf_opp[]')[nr].value + document.getElementsByName('plaat_tot_verf_opp[]')[nr].value)).toFixed( 2 ) } } Form (in loop): PHP Code: <tr> <td><select name="overig_omsch[]" > <option></option> <option value=Engineering>Engineering</option> <option value=Inkoop bev.middelen>Inkoop bev.middelen</option> <option value=Inkoop snijwerk>Inkoop snijwerk</option> <option value=Spuiten>Spuiten</option> <option value=Stralen>Stralen</option> <option value=Transport>Transport</option> </select> </td> <td><select name="overig_eenh[]" onChange="overig_tot_abs(this, 0)" > <option></option> <option value="totaal">Totaal</option> <option value="kg">Per Kg</option> <option value="verf_opp">Per 1m2</option> </td> <td><input type="text" name="overig_prijs[]" size="10" value="" /></td> <td><input type="text" name="overig_totaal[]" size="10" style="text-align:right;background-color: #f1f1f1" value="" readonly="readonly" /></td> <td><input type="text" name="overig_opmerkingen[]" size="75" value="" /></td> </tr> I have a page that loads various "applications" into an iframe inside the main page. One of the applications loaded calls a javascript function that is loaded with the "application" page. It works great in Safari, Chrome & Firefox but error's out in IE8 - "Object doesn't support this action". Anyone know why ? Have other calls that work but this one is the only one that uses href Thanks, JerryB [CODE] <div id = 'trainingsubmitbutton' style='display:none;'><a href='javascript: submitdata(0)'>Submit This Record</a></div> [CODE] I have some javascript code: first it gets string of the url in the address bar then it splits the string at the ? and grabs the right half it then makes an IFrame go to that string(which is yet another url I would manually insert) here is the code: Code: function redirect(){ var raw=window.document.location.href; if(content_address_start=raw.indexOf("?")!=-1){ var content_address=raw.split("frame.html?")[1]; window.document.getElementById('content').src=content_address; } } 'content' is the id of the IFrame, and frame.html is the html file this code is inside. Ok, so everything works perfectly when I test this code offline, but as soon as I load it to my website, and the .src line occurs, it just loads a blank page in the IFrame. What could be causing this? Perhaps certain sites will not allow themselves to be inside iframes? Much thanks in advance. I hope I gave enough information and relayed my problem clearly. EDIT: It seems that the code works on other sites, just not youtube. Why would it do this and are there any ways around it? Hi Guys, I'm trying to do up a contact form that after a user submits the information, the drop down contact box will slide back up instead of redirecting to another page. The script works fine in Chrome and Safari, but Firefox and IE keeps redirecting to the php page. Hope someone can shed some light here, thanks! Html form: Code: <div class="left"> <!-- Login Form --> <form class="clearfix" action="contactengine.php" name="cform" method="post"> <h4>Drop us a mail</h4> <label class="grey" for="emailName">Name:</label> <input class="field" type="text" name="emailName" id="emailName" value="" size="23" /> <label class="grey" for="emailFrom">Email Address:</label> <input class="field" type="text" name="emailFrom" id="emailFrom" value="" size="23" /> <label class="grey" for="message">Message:</label> <textarea type="text" name="message" id="message" size="23"></textarea> <div class="clear"></div> <input type="submit" rows="" cols="" name="submit" value="Submit" class="bt_register" /> <span id="messageSent">Message sent successfully!</span> </form> <script language="JavaScript" type="text/javascript"> //You should create the validator only after the definition of the HTML form var frmvalidator = new Validator("cform"); frmvalidator.addValidation("emailName","req","Please enter your Name"); frmvalidator.addValidation("emailName","maxlen=20", "Max length for Name is 20"); frmvalidator.addValidation("emailFrom","maxlen=50", "Max length for email is 50"); frmvalidator.addValidation("emailFrom","req","Please enter your Email"); frmvalidator.addValidation("emailFrom","email","Please enter a valid email"); </script> </div> <div class="left right"> <!-- Register Form --> <h4>Contact Details</h4> <p class="grey"><b>XXX<br /></b>XXX<br />XXX<br />XXX</p> <p class="grey">T: 999<br />F: 999</p> <h5>Stalk Us</h5> <a href="index.html"><img src="misc/fb.png" border="0" alt="Facebook" /></a> <a href="index.html"><img src="misc/twit.png" border="0" alt="Twitter" /></a> </div> </div> </div> <!-- The tab on top --> <div class="tab"> <ul class="login"> <li class="left"> </li> <li>Hello there</li> <li class="sep">|</li> <li id="toggle"> <a id="open" class="open" href="#">Contact Us</a> <a id="close" style="display: none;" class="close" href="#">Close Panel</a> </li> <li class="right"> </li> </ul> </div> <!-- / top --> The Slider JS: Code: $(document).ready(function() { // Expand Panel $("#open").click(function(){ $("div#panel").slideDown("slow"); }); // Collapse Panel $("#close").click(function(){ $("div#panel").slideUp("slow"); }); // Switch buttons from "Hey There | Contact us" to "Close Panel" on click $("#toggle a").click(function () { $("#toggle a").toggle(); }); //submission scripts $('div#panel').submit( function(){ //statements to validate the form var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; var email = document.getElementById('emailFrom'); if (!filter.test(emailFrom.value)) { $('.email-missing').show(); } else {$('.email-missing').hide();} if (document.cform.emailName.value == "") { $('.name-missing').show(); } else {$('.name-missing').hide();} if (document.cform.message.value == "") { $('.message-missing').show(); } else {$('.message-missing').hide();} if ((document.cform.emailName.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "")){ return false; } if ((document.cform.emailName.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) { //hide the form $('.div#panel').hide(); //show the loading bar $('.loader').append($('.bar')); $('.bar').css({display:'block'}); //send the ajax request $.post('contactengine.php',{emailName:$('#emailName').val(), emailFrom:$('#emailFrom').val(), message:$('#message').val()}, //return the data function(data){ //hide the graphic $('.bar').css({display:'none'}); $('.loader').append(data); }); //waits 2000, then closes the form and fades out $("#messageSent").show("slow"); setTimeout('$("#toggle a").toggle(); $("div#panel").slideUp("slow")', 2000); //stay on the page return false; } }); }); The PHP Code: PHP Code: <?php $EmailFrom = "xxx@xxx.com"; $EmailTo = "xxx@xxx.com"; $Subject = Trim(stripslashes($_POST['Webmail'])); $Name = Trim(stripslashes($_POST['emailName'])); $Email = Trim(stripslashes($_POST['emailFrom'])); $Message = Trim(stripslashes($_POST['message'])); // validation $validationOK=true; if (!$validationOK) { print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; exit; } // prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $Name; $Body .= "\n"; $Body .= "Email Adress: "; $Body .= $Email; $Body .= "\n"; $Body .= "Message: "; $Body .= $Message; $Body .= "\n"; // send email $success = mail($EmailTo, Webmail, $Body, "From: <$EmailFrom>"); // redirect to success page if ($success){ print "<meta http-equiv=\"refresh\" content=\"0;URL=success.html\">"; } else{ print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">"; } ?> Code: I am trying to get the following image fade code to work but can't seem to figure out what the problem is. The images appear quickly (don't fade one to the other) in Firefox and Google and in IE8 when the image fades, even though the images are the same size, the new image starts out smaller and grows to the final size. Any suggestions are greatly appreciated. <SCRIPT LANGUAGE="JavaScript"> <!-- Begin // Set slideShowSpeed (milliseconds) var slideShowSpeed = 5000; // Duration of crossfade (seconds) var crossFadeDuration = 2500; // Specify the image files var Pic = new Array(); Pic[0] = 'images/Monsanto.gif' Pic[1] = 'images/Test2.jpg' Pic[2] = 'images/Test3.jpg' Pic[3] = 'images/Test4.jpg' Pic[4] = 'images/Test5.jpg' Pic[5] = 'images/Test1.jpg' var t; var j = 0; var p = Pic.length; var preLoad = new Array(); for (i = 0; i < p; i++) { preLoad[i] = new Image(); preLoad[i].src = Pic[i]; } preLoad.sort(function() {return 0.5 - Math.random()}); function runSlideShow() { if (document.all) { document.images.SlideShow.style.filter="blendTrans(duration=2)"; document.images.SlideShow.style.filter="blendTrans(duration=crossFadeDuration)"; document.images.SlideShow.filters.blendTrans.Apply(); } document.images.SlideShow.src = preLoad[j].src; if (document.all) { document.images.SlideShow.filters.blendTrans.Play(); } j = j + 1; if (j > (p - 1)) j = 0; t = setTimeout('runSlideShow()', slideShowSpeed); } // End --> </script> Every time i click on one of the said elements, it puts "undefined" into the textbox each time i click on an element. it seems to me that the Key_Table[x] is not getting passed correctly. How do i make sure that this is getting passed correctly? Here's my Code: Code: <script type='text/javascript'> // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); } function LoadEventListeners() { var Key_Table = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]; // Create event Listeners for the alphabetic keys for(var x = 0; x < Key_Table.length; x++) { Key_Table[x] = document.getElementById(Key_Table[x]); Key_Table[x].addEventListener("click", function(){ InsertChar(Key_Table[x]); }, false); } } function InsertChar(Char) { alert("Char is:" + Char); // Textbox data document.getElementById('TextData').value = document.getElementById('TextData').value + Char; } </script> Hi everyone. Here is the code I am using to flip an image 3 times (Blank -> X, X-> O and O back to blank) Code: function flipBox(img) { var tmpname; if(img.src=="http://www.riddlesforall.com/logic/n.gif") { img.src = "http://www.riddlesforall.com/logic/x.gif"; tmpname = img.name; document.mainform.elements[tmpname].value = 1; document.getElementById(img.name).value = 1; } else if(img.src=="http://www.riddlesforall.com/logic/x.gif") { var finaltest = checkDoubles(img.name); if(finaltest=="false") { img.src = "http://www.riddlesforall.com/logic/o.gif"; tmpname = img.name; document.mainform.elements[tmpname].value = 3; document.getElementById(img.name).value = 3; } else { img.src = "http://www.riddlesforall.com/logic/n.gif"; } } else if(img.src=="http://www.riddlesforall.com/logic/o.gif") { img.src = "http://www.riddlesforall.com/logic/n.gif"; tmpname = img.name; document.mainform.elements[tmpname].value = 0; document.getElementById(img.name).value = 0; } showVals(); } I had it working, previously, and everything was fine, but now, for some odd reason I cannot figure out, it is changing the names of the image files to absurdly long gibberish, and I cannot flip any images at all, clicking does nothing. Here is an example of what it changes the names to: Code: <img src="data:image/gif;base64,R0lGODlhGQAZAIAAAP///wAAACH5BAEAAAAALAAAAAAZABkAAAIXhI+py+0Po5y02ouz3rz7D4biSJamWAAAOw==" height=20 width=20 id=1-0-0 name=A1B1 onclick="flipBox(this);" class=gridbox> There are 3 images - N.gif (blank) X.gif (An X) and O.gif I do not understand why it is changing the names like this? As I said, it was working fine before, and now this. Having trouble getting this plugin to work.. jparallax - see here for more info - http://webdev.stephband.info/parallax.html Now I have this plugin working separately, on its own page, just fine. see here - http://bit.ly/hPpSAC But when I went back, to my own page, and tried to incorporate it into the background of my site, I was able to get the look fine, but the movement isn't working. see here - http://bit.ly/ee52Iv I've tried everything I could to get it working.. Maybe someone here could troubleshoot? It would be a huge help, seriously. Thanks. Hello all, I've got a problem with a JS dropdown menu that I'm using. It's an unordered HTML list that is driven by a JS file. The menu is at Watt You Need Electrical - Offering Electrical Services For Geelong, Bellarine Peninsula & The Surf Coast Initially when I got the menu template all the top level items and all the list items were coded as links. What I've done is make the Electrical heading just text and the two dropdown list items below it are still links. The menu works both on a desktop with a pointer and also on a mobile device by touch. The problem is that on a mobile device when I touch the Electrical heading the dropdown doesn't appear. The Solar heading and the dropdown below it work fine because the Solar heading is still a link. Obviously I've created the problem by changing the Electrical heading to text from a link but I'd like to be able to have it that way. I've tested using some online mobile device emulators and it works OK there but when I physically test on an Iphone 5 the bug is there. I haven't been able to get my hands on any other phones or devices to test yet so don't know if it's a problem just with Iphones or Ipads. I've had a look through the Dropdown.src.js file but it's way beyond me, I've listed both the HTML and JS file below. Code: <!DOCTYPE html> <html> <head> <title>Watt You Need Electrical - Offering Electrical Services For Geelong, Bellarine Peninsula & The Surf Coast</title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <meta name="description" content="Watt You Need Electrical is your one stop shop for all types of electrical services. Whether you need some domestic, commercial, or even industrial electrical work done we can help. We also can advise on and install solar power systems and split air conditioners." /> <meta name="keywords" content="electrical services" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" type="text/css" href="css/styles.css" media="Screen" /> <link rel="stylesheet" type="text/css" href="css/mobile.css" media="handheld" /> <link media="only screen and (max-device-width: 480px)" href="css/mobile.css" type="text/css" rel="stylesheet" /> <script> // initialise the drop-down menus runOnLoad(Dropdown.initialise); </script> </head> <body> <div id="wrapper"> <a href="tel://+61425859742"><div id="mobile_header"></div></a> <a href="tel://+61425859742"><div id="phoneBlock"></div></a> <div id="header"></div> <div id="nav"> <ul class="dropdown"> <li> <a href="index.html">Home</a> </li> <li>Electrical <ul> <li> <a href="domestic_electrician.html">Domestic</a> </li> <li> <a href="electrical_contractors.html">Commercial/Industrial</a> </li> </ul> </li> <li> <a href="air_conditioner_installation.html">Air Conditioners</a> </li> <li> <a href="solar_power_systems.html">Solar</a> <ul> <li><a href="solar_system_maintenance.html">Maintenance</a> </li> <li><a href="solar_energy_facts.html">About Solar</a> </li> </ul> </li> <li> <a href="b_type_gas_service.html">Type B Gas</a> </li> <li> <a href="formgenerator/forms/contact.html">Contact Us</a> </li> </ul> </div> <div id="content-2"> <div class="clear"> </div> <div id="top_border"></div> <div id="content-2-1"> <span class="blackheading">Watt You Need Electrical - Offering Electrical Services For Geelong, Bellarine Peninsula & The Surf Coast</span> <p>Watt You Need Electrical Services can help you with all your electrical needs. We're not one of the big franchise electrical contractors so we can take that extra bit of time and effort to make sure you get the best service and advice. <br /><br /> If it's just an extra power point you need all the way to a complete house rewire, thinking about making the switch to solar power, or if you want a split airconditioner to keep your house or business cool and comfortable, our focus is on exceeding our customer's expectations and providing the best quality job at a competitive price. <br /><br /> Our service doesn't just stop at <a href="domestic_electrician.html">domestic electrical</a> and <a href="solar_power_systems.html">solar power</a>, we can also attend to your <a href="electrical_contractors.html">commercial and industrial electrical</a> needs and we specialise in <a href="b_type_gas_service.html">B Class gas appliance</a> repair and maintenance. Our range of services and quality workmanship are what sets us apart from other electrical contractors. <br /><br /> <a href="formgenerator/forms/contact.html">Contact us</a> today and let Watt You Need Electrical take care of your domestic, solar, air conditioning and commercial and industrial electrical services. </p> </div> <div id="bottom_border"></div> </div> <div id="footer"> <table class="tableFooter"> <tr><td>Watt You Need Electrical Pty. Ltd. © 2014</td></tr> </table> </div> </div> </body> </html> Code: /* Dropdown.js Creates touch-friendly drop-down menus Created by Stephen Morley - http://code.stephenmorley.org/ - and released under the terms of the CC0 1.0 Universal legal code: http://creativecommons.org/publicdomain/zero/1.0/legalcode */ // create the Dropdown object var Dropdown = (function(){ // the delay, in milliseconds var DELAY = 250; // the list of menus var menus = []; // Initialises the drop-down menus. function initialise(){ // listen for touch events on the document if appropriate if ('createTouch' in document){ document.body.addEventListener('touchstart', handleTouchStart, false); } // loop over the menus, converting them var menus = document.querySelectorAll('ul.dropdown'); for (var i = 0; i < menus.length; i ++) applyTo(menus[i]); } /* Handles a touch start event. The parameter is: * * e - the event */ function handleTouchStart(e){ // determine whether any menu is open var isOpen = false; for (var i = 0; i < menus.length; i ++){ if (menus[i].isOpen) isOpen = true; } // return immediately if all menus are closed if (!isOpen) return; // move up the document tree until we reach the root node var node = e.target; while (node != null){ // return immediately if we are inside a drop-down menu if (/\bdropdown\b/.test(node.className)) return; // move onto the parent node node = node.parentNode; } // close all menus close(); } /* Closes all menus except the specified menu. The parameter is: * * menu - a menu not to close; this parameter is optional */ function close(menu){ // loop over the menus, closing them for (var i = 0; i < menus.length; i ++){ if (menus[i] != menu) menus[i].close(); } } /* Creates a drop-down menu. The parameter is: * * node - either the DOM node of the menu or the ID of the node */ function applyTo(node){ // fetch the DOM node if a string was supplied if (typeof node == 'string') node = document.getElementById(node); // create and store the new menu menus.push(new Menu(node)); } /* Creates a drop-down menu. The parameter is: * * node - the DOM node of the menu */ function Menu(node){ // store the node this.node = node; // update the class name node.className += ' dropdownJavaScript'; // listen for mouse events if ('addEventListener' in node){ node.addEventListener( 'mouseover', this.bind(this.handleMouseOver), false); node.addEventListener('mouseout', this.bind(this.handleMouseOut), false); node.addEventListener('click', this.bind(this.handleClick), false); }else{ node.attachEvent('onmouseover', this.bind(this.handleMouseOver)); node.attachEvent('onmouseout', this.bind(this.handleMouseOut)); node.attachEvent('onclick', this.bind(this.handleClick)); } // listen for touch events if appropriate if ('createTouch' in document){ node.addEventListener('touchstart', this.bind(this.handleClick), false); } } // whether the menu is open Menu.prototype.isOpen = false; // the timeout Menu.prototype.timeout = null; /* Binds the specified function to the current object. The parameter is: * * f - the function */ Menu.prototype.bind = function(f){ // return the bound function var thisObject = this; return function(){ f.apply(thisObject, arguments); } } /* Handles a mouse over event. The parameters a * * e - the event * immediate - true to open the menu without a delay */ Menu.prototype.handleMouseOver = function(e, immediate){ // clear the timeout this.clearTimeout(); // find the parent list item var item = ('target' in e ? e.target : e.srcElement); while (item.nodeName != 'LI' && item != this.node) item = item.parentNode; // if the target is within a list item, set the timeout if (item.nodeName == 'LI'){ this.toOpen = item; this.timeout = window.setTimeout(this.bind(this.open), (immediate ? 0 : DELAY)); } } // Handles a mouse out event. Menu.prototype.handleMouseOut = function(){ // clear the timeout this.clearTimeout(); // set the timeout this.timeout = window.setTimeout(this.bind(this.close), DELAY); } /* Handles a click event. The parameter is: * * e - the event */ Menu.prototype.handleClick = function(e){ // close any other menus close(this); // find the parent list item var item = ('target' in e ? e.target : e.srcElement); while (item.nodeName != 'LI' && item != this.node) item = item.parentNode; // check that the target is within a list item if (item.nodeName == 'LI'){ // check whether the item has a closed submenu var submenu = this.getChildrenByTagName(item, 'UL'); if (submenu.length > 0 && !/\bdropdownOpen\b/.test(item.className)){ // open the submenu this.handleMouseOver(e, true); // prevent the default action if ('preventDefault' in e){ e.preventDefault(); }else{ e.returnValue = false; } } } } // Clears the timeout. Menu.prototype.clearTimeout = function(){ // clear the timeout if (this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } } // Opens the last item hovered over. Menu.prototype.open = function(){ // store that the menu is open this.isOpen = true; // loop over the list items with the same parent var items = this.getChildrenByTagName(this.toOpen.parentNode, 'LI'); for (var i = 0; i < items.length; i ++){ // check whether there is a submenu var submenu = this.getChildrenByTagName(items[i], 'UL'); if (submenu.length > 0){ // check whether the submenu should be opened or closed if (items[i] != this.toOpen){ // close the submenu items[i].className = items[i].className.replace(/\bdropdownOpen\b/g, ''); this.close(items[i]); }else if (!/\bdropdownOpen\b/.test(items[i].className)){ // open the submenu items[i].className += ' dropdownOpen'; // determine the location of the edges of the submenu var left = 0; var node = submenu[0]; while (node){ left += node.offsetLeft; node = node.offsetParent; } right = left + submenu[0].offsetWidth; // move the submenu to the right of the item if appropriate if (left < 0) items[i].className += ' dropdownLeftToRight'; // move the submenu to the left of the item if appropriate if (right > document.body.clientWidth){ items[i].className += ' dropdownRightToLeft'; } } } } } /* Closes the menus within the specified node. The parameter is: * * node - the node; if omitted, all menus are closed */ Menu.prototype.close = function(node){ // if no node was specified, close all menus if (!node){ this.isOpen = false; node = this.node; } // loop over the items, closing their submenus var items = node.getElementsByTagName('li'); for (var i = 0; i < items.length; i ++){ items[i].className = items[i].className.replace(/\bdropdownOpen\b/g, ''); } } /* Returns an array containing the children of the specified node with the * specified tag name. The parameters a * * node - the node * tagName - the tag name */ Menu.prototype.getChildrenByTagName = function(node, tagName){ // initialise the list of children var result = []; // loop over the children, adding those with the right tag name to the list for (var i = 0; i < node.childNodes.length; i ++){ if (node.childNodes[i].nodeName == tagName){ result.push(node.childNodes[i]); } } // return the children return result; } // return the public API return { initialise : initialise, applyTo : applyTo }; })(); Any help is appreciated. Hey guys..... I've built a tool where users can search for something & the results show up in a select list as selectable options..... sometimes the results can take a few seconds to load depending on how many results there are... so I was attempting to show some "Results are loading" text when they search, & then hide it when they are displayed. However for some reason it's not working correctly...... both commands don't appear to work until the select list options have loaded & hence rendering them redundant.... I have tried putting them inside separate functions but no change in the behavior. What basically happens is I press the button to search & it searches & once the results show up so does the loading text.... however if I include the hide text command then the text doesn't show at all as it's hidden as soon as it's shown. Here is the code I am using.. PHP Code: function searchCats(text) { // Set URL for ajax request var url = 'search_cats.php?search_text='+text; // Set up element we're modifying var results = document.getElementById('cat_list'); // Trim string text.replace(/^ss*/, '').replace(/ss*$/, ''); if (text.length < 3) { alert('Please enter a search string more than 2 characters.'); return; } // Send the request, giving it an anonymous function that acts as the oncomplete event ajaxRequest(url, (function(ajaxResponse) { /* Deal with results */ // First we remove all current childs while(results.hasChildNodes()) { while (results.childNodes.length >= 1) { results.removeChild(results.firstChild); } } if (ajaxResponse == '') { // Display no results text document.getElementById('no_results').style.display='block'; } else { // Hide no results text document.getElementById('no_results').style.display='none'; // Display loading text document.getElementById('loading_results').style.display='block'; // Check for occurence of cat seperator (if not there then we know we only have one results) var sep_found = ajaxResponse.indexOf('!@!'); if (sep_found === -1) { // One result only // Seperate ID & cat name var parts = ajaxResponse.split('^@^'); // Create option element var option = document.createElement('option'); // Add attribute option.setAttribute('value', parts[0]); // Create text node var textNode = document.createTextNode(parts[1]); // Append text node to option element option.appendChild(textNode); // Now append option element to select list results.appendChild(option); } else { // Seperate cat data var cats = ajaxResponse.split('!@!'); // Loop through cat data for(i = 0; i < cats.length; i++) { // Seperate ID & cat name var parts = cats[i].split('^@^'); // Create option element var option = document.createElement('option'); // Add attribute option.setAttribute('value', parts[0]); // Create text node var textNode = document.createTextNode(parts[1]); // Append text node to option element option.appendChild(textNode); // Now append option element to select list results.appendChild(option); } } } })); // Hide loading text document.getElementById('loading_results').style.display='none'; } Thanks guys! I have a form and javascript that doesn't work correctly. I think there's a problem with the javascript, but it's possible the form is the culprit. I'm new at this. Here is the form code for a search boxx: Code: <form id="search" method="get" name="search" action="promotions.html"> <input type="text" size="15" name="ws" maxlength="500" value="pen, keychain, etc." onfocus="this.value='';return false;" /> <button type="submit" value="Search">Go</button> <input type="hidden" name="ID" value="64857723-2161-4778-BDEB-3EE622F6CFF3" /> </form> Here is the javascript that's in the head of /promotions.html: Code: <script type="text/javascript"> function FrameRedirect() { var q = window.location.search; q = (q.length > 1) ? q.substring(1, q.length) : 0; var s = q.substring(0, 2); switch (s) { case 'ws': q = 'http://www.asiconnection.com/ProductSearch/LinkInQS.aspx?'+q; document.getElementById('Content').className = 'active'; break; case 'bn': q = q.substring(3,q.length); document.getElementById('RD2').className = 'active'; break; default: document.getElementById('RD1').className = 'active'; break; } iframe = '<iframe id="frame" src="'+q+'" width="780" scrolling="yes" frameborder="0" height="500"></iframe>'; document.getElementById('Content').innerHTML = iframe; } </script> The search box code is suppose to send the inputted search word to the javascript on /promotions.html page and then load the search results http://www.asiconnection.com/Product.../LinkInQS.aspx into the iframe on that page. The only thing that appears in that iframe is "Oops. Firefox cannot find productsearch" Can someone help me figure this out? Thanks in advance. I found this script, and it works great: Code: <script type="text/javascript"> function disable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","true"); } } </script> I tried to make the inverse by simply reversing the setAttribute() like so: Code: <script type="text/javascript"> function enable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","false"); } } </script> But that didn't do it. Can someone show me why, and how to fix it? Here's the sample form which I'm trying to test it on: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> disable<br/> <input type="radio" name="test" onclick="enable('D1')" /> enable<br/> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /><br/> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /><br/> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /><br/> </fieldset> </form> Edit: The ultimate goal which I'm working toward now (step by step =) is to have a form more like: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /> </fieldset> <input type="radio" name="test" onclick="disable('D2')" /> <fieldset id="D2"> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /> </fieldset> <input type="radio" name="test" onclick="disable('D3')" /> <fieldset id="D3"> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /> </fieldset> </form> And have the fieldsets enable and disable according the selection of the radio buttons. Also, the fieldsets (and their ID's) will be dynamically generated via PHP Thanks-a-bunch, ~ Mo Hi I want to pass a strings from JS client to PHP server and vice versa. Problem is that I can't find a simple method of escaping them that gives consistent results. I've tried escape, unescape, urlencode and urldecode, but there are problems with some characters eg + From what I've read, JSON is the most reliable way to do this. I've figured out how to use json_encode to get a php string to a javascript variable, but I can't go the other way. How do I get the JSON string that represents a javascript object? Thanks for any help. I wasn't quite sure where to post this request as its JSON, javascript and php, so please tell me if I'm in the wrong place. I am sorry if this is a stupid question. I have never really used javascript before. I found some code online that I tried to piece together so I might not even be going about this the right way. I want the background to take up 100% and resize with the browser. That works fine. I also want the text "welcome to the ahi life" stick to the bottom left hand corner and the enter button to stick to the bottom right. I would like these to resize with the browser as well. It all kind of works, except the first time you load the page the text and the button are much smaller than I would like them to be. If you refresh the page everything is correct. The url is http://www.ahiapparel.com/landing.html Code: <style> * { margin: 0; padding: 0; } #bg { position: fixed; top: 0; left: 0; } .bgwidth { width: 100%; } .bgheight { height: 100%; } #page-wrap { position:absolute; bottom:0; left:20px; width: 700px; margin: 50px auto;} #welcometext { position: fixed; bottom: 20px; left: 25px; } .welcometextwidth { width: 7%; } .welcometextheight { height: 7%; } #entertext { position: fixed; bottom: 20px; right: 25px; } .entertextwidth { width: 7%; } .entertextheight { height: 7%; } </style> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(function funct1() { var theWindow = $(window), $bg = $("#bg"), aspectRatio = $bg.width() / $bg.height(); function resizeBg() { if ( (theWindow.width() / theWindow.height()) < aspectRatio ) { $bg .removeClass() .addClass('bgheight'); } else { $bg .removeClass() .addClass('bgwidth'); } } theWindow.resize(function() { resizeBg(); }).trigger("resize"); }); $(function funct2() { var theWindow = $(window), $welcometext = $("#welcometext"), aspectRatio = $welcometext.width() / $welcometext.height(); function resizewelcometext() { if ( (theWindow.width() / theWindow.height()) < aspectRatio ) { $welcometext .removeClass() .addClass('welcometextheight'); } else { $welcometext .removeClass() .addClass('welcometextwidth'); } } theWindow.resize(function() { resizewelcometext(); }).trigger("resize"); }); $(function funct3() { var theWindow = $(window), $entertext = $("#entertext"), aspectRatio = $entertext.width() / $entertext.height(); function resizeentertext() { if ( (theWindow.width() / theWindow.height()) < aspectRatio ) { $entertext .removeClass() .addClass('entertextheight'); } else { $entertext .removeClass() .addClass('entertextwidth'); } } theWindow.resize(function() { resizeentertext(); }).trigger("resize"); }); </script> My best guess is that either the functions or some of the variables are conflicting somehow, but I have tried just about everything to fix it. Any help would be much appreciated. Thanks! |