JavaScript - Is This Script Scalable And Formatted Correctly?
Hi guys,
Just wondering if this javascript is valid. I have about 150 variables, and I want to check, before I start writing it all out. Anything that could reduce it a bit would be great, save time and make the code more efficient! By the way, all values are numbers entered in a html text field. The script does calculations on it, and posts the result to a hidden field, which is submitted to a php email script. Code: <script language="JavaScript"> function calculate() { "use strict"; var sofa_3_seaterX = (document.form1.sofa_3_seater.value * 6); var sofa_2_seaterX = (document.form1.sofa_2_seater.value * 35); var armchair_largeX = (document.form1.armchair_large.value * 9); var armchair_smallX = (document.form1.armchair_small.value * 2); var wall_unitX = (document.form1.wall_unit.value * 3); var total = (sofa_3_seaterX + sofa_2_seaterX + armchair_largeX + armchair_smallX + wall_unitX); document.form1.total.value = total; } </script> Similar TutorialsI have been using the following script for some time and it has only just been made known to me that it fails on todays date ! not sure if this is the case for other days but the days of the week are all messed up and do not show correctly for a date in June 2011. Code: var ds_i_date = new Date(); ds_c_month = ds_i_date.getMonth() + 1; ds_c_year = ds_i_date.getFullYear(); // Get Element By Id function ds_getel(id) { return document.getElementById(id); } // Get the left and the top of the element. function ds_getleft(el) { var tmp = el.offsetLeft; el = el.offsetParent while(el) { tmp += el.offsetLeft; el = el.offsetParent; } return tmp; } function ds_gettop(el) { var tmp = el.offsetTop; el = el.offsetParent while(el) { tmp += el.offsetTop; el = el.offsetParent; } return tmp; } // Output Element var ds_oe = ds_getel('ds_calclass'); // Container var ds_ce = ds_getel('ds_conclass'); // Output Buffering var ds_ob = ''; function ds_ob_clean() { ds_ob = ''; } function ds_ob_flush() { ds_oe.innerHTML = ds_ob; ds_ob_clean(); } function ds_echo(t) { ds_ob += t; } var ds_element; // Text Element... var ds_monthnames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; // You can translate it for your language. var ds_daynames = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]; // You can translate it for your language. // Calendar template function ds_template_main_above(t) { return '<table cellpadding="3" cellspacing="1" class="ds_tbl">' + '<tr>' + '<td class="ds_head" style="cursor: pointer" onclick="ds_py();"><<</td>' + '<td class="ds_head" style="cursor: pointer" onclick="ds_pm();"><</td>' + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="3">[Close]</td>' + '<td class="ds_head" style="cursor: pointer" onclick="ds_nm();">></td>' + '<td class="ds_head" style="cursor: pointer" onclick="ds_ny();">>></td>' + '</tr>' + '<tr>' + '<td colspan="7" class="ds_head">' + t + '</td>' + '</tr>' + '<tr>'; } function ds_template_day_row(t) { return '<td class="ds_subhead">' + t + '</td>'; // Define width in CSS, XHTML 1.0 Strict doesn't have width property for it. } function ds_template_new_week() { return '</tr><tr>'; } function ds_template_blank_cell(colspan) { return '<td colspan="' + colspan + '"></td>' } function ds_template_day(d, m, y) { return '<td class="ds_cell" onMouseout="this.style.background=\'#EEE\';" onMouseover="this.style.background=\'#999\';" onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</td>'; // Define width the day row. } function ds_template_main_below() { return '</tr>' + '</table>'; } // This one draws calendar... function ds_draw_calendar(m, y) { // First clean the output buffer. ds_ob_clean(); // Here we go, do the header ds_echo (ds_template_main_above(ds_monthnames[m - 1] + ' ' + y)); for (i = 0; i < 7; i ++) { ds_echo (ds_template_day_row(ds_daynames[i])); } // Make a date object. var ds_dc_date = new Date(); ds_dc_date.setMonth(m - 1); ds_dc_date.setFullYear(y); ds_dc_date.setDate(1); if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) { days = 31; } else if (m == 4 || m == 6 || m == 9 || m == 11) { days = 30; } else { days = (y % 4 == 0) ? 29 : 28; } var first_day = ds_dc_date.getDay(); var first_loop = 1; // Start the first week ds_echo (ds_template_new_week()); // If sunday is not the first day of the month, make a blank cell... if (first_day != 0) { ds_echo (ds_template_blank_cell(first_day)); } var j = first_day; for (i = 0; i < days; i ++) { // Today is sunday, make a new week. // If this sunday is the first day of the month, // we've made a new row for you already. if (j == 0 && !first_loop) { // New week!! ds_echo (ds_template_new_week()); } // Make a row of that day! ds_echo (ds_template_day(i + 1, m, y)); // This is not first loop anymore... first_loop = 0; // What is the next day? j ++; j %= 7; } // Do the footer ds_echo (ds_template_main_below()); // And let's display.. ds_ob_flush(); // Scroll it into view. //ds_ce.scrollIntoView(); } // A function to show the calendar. // When user click on the date, it will set the content of t. function ds_sh(t) { // Set the element to set... ds_element = t; // Make a new date, and set the current month and year. var ds_sh_date = new Date(); ds_c_month = ds_sh_date.getMonth() + 1; ds_c_year = ds_sh_date.getFullYear(); // Draw the calendar ds_draw_calendar(ds_c_month, ds_c_year); // To change the position properly, we must show it first. ds_ce.style.display = ''; // Move the calendar container! the_left = ds_getleft(t); the_top = ds_gettop(t) + t.offsetHeight; ds_ce.style.left = the_left + 'px'; ds_ce.style.top = the_top + 'px'; // Scroll it into view. //ds_ce.scrollIntoView(); } // Hide the calendar. function ds_hi() { ds_ce.style.display = 'none'; } // Moves to the next month... function ds_nm() { // Increase the current month. ds_c_month ++; // We have passed December, let's go to the next year. // Increase the current year, and set the current month to January. if (ds_c_month > 12) { ds_c_month = 1; ds_c_year++; } // Redraw the calendar. ds_draw_calendar(ds_c_month, ds_c_year); } // Moves to the previous month... function ds_pm() { ds_c_month = ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid. // We have passed January, let's go back to the previous year. // Decrease the current year, and set the current month to December. if (ds_c_month < 1) { ds_c_month = 12; ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid. } // Redraw the calendar. ds_draw_calendar(ds_c_month, ds_c_year); } // Moves to the next year... function ds_ny() { // Increase the current year. ds_c_year++; // Redraw the calendar. ds_draw_calendar(ds_c_month, ds_c_year); } // Moves to the previous year... function ds_py() { // Decrease the current year. ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid. // Redraw the calendar. ds_draw_calendar(ds_c_month, ds_c_year); } // Format the date to output. function ds_format_date(d, m, y) { // 2 digits month. m2 = '00' + m; m2 = m2.substr(m2.length - 2); // 2 digits day. d2 = '00' + d; d2 = d2.substr(d2.length - 2); // YYYY-MM-DD return d2 + '-' + m2 + '-' + y; } // When the user clicks the day. function ds_onclick(d, m, y) { // Hide the calendar. ds_hi(); // Set the value of it, if we can. if (typeof(ds_element.value) != 'undefined') { ds_element.value = ds_format_date(d, m, y); // this part is a personal bit of code to allow my page to update correctly and in time. if("fireEvent" in ds_element) ds_element.fireEvent("onChange"); else { var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); ds_element.dispatchEvent(evt); } // // Maybe we want to set the HTML in it. } else if (typeof(ds_element.innerHTML) != 'undefined') { ds_element.innerHTML = ds_format_date(d, m, y); // I don't know how should we display it, just alert it to user. } else { alert (ds_format_date(d, m, y)); } } I'm a bit confused as to how to use the getDay() function. I have an input field with a date in the following format 12.06.2012 and I'd like to run the function to get the day of the week from any date in that input field. All the examples I have found using getDay(), do so from a new Date() and not from one existing in an input field. Also my format is not the usual 06/12/2012. Any help appreciated. Here's what I have tried: Code: var d="12.06.2012"; var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; document.write("The day is " + weekday[d.getDay()]); So I'm picking up on a project that was left off by another developer. He developed the search engine for this website using mustache.js as a templating plugin. However, I have this giant if/else statement in the Javascript to implement it in the template.. but it's ugly in my opinion so I'm curious on if anybody has a better way of going about this. Here is my template in the view: Code: <script id="search_result_item" type="x-tmpl-mustache"> <div id="Box_Book1" class="clearfix search-result-item"> <a href="{{encore_url}}"> <img id="Image1" src="{{ image_url }}" onerror="this.src = 'http://origin.syndetics.com/index.php?upc=x/MC.gif&client=stlip&type=hw7';" class="image {{material_type}}" /> <span class="{{ label_class }}">{{ label_text }}</span> </a> <div class="title-container"> <span id="textspan5" class="more-details"> <a href="{{ encore_url }}" target="_blank">+ More Details</a> </span> <div class="text-title1-container"> <p class="title"> {{ title }} </p> </div> </div> <p id="Text_Author1"> {{ author }}<br /> </p> </div> </script> Here is my Javascript that is rending into the template: Code: // this is gnarly i know..hopefully temporary var item_type = result.material_type; var label_class; var label_text; // This needs rewritten too once search is written in different format if(item_type == 'z') { // EBook label_class = 'ebook'; label_text = 'EBook'; } else if(item_type == 'w') { // EAudio label_class = 'eaudio'; label_text = 'EAudio'; } else if(item_type == 'x') { // EVideo label_class = 'evideo'; label_text = 'EVideo'; } else if(item_type == 'h') { // EMagazine label_class = 'emag'; label_text = 'EMag'; } var css_image_class = args.material_type; if (css_image_class == '24_7_online_library') { css_image_class = 'online_library'; } var template_args = { 'image_url' : image_url, 'error_image_url' : error_image_url, 'author' : result.author, 'title' : result.title, 'year' : '(' + result.year + ')', 'encore_url' : encore_url, 'material_type' : css_image_class, 'label_class' : label_class, 'label_text' : label_text }; div.html(Mustache.render(result_item_template, template_args)); Thank you for any ideas on how to make it prettier.. the item_type is what's terrifying ugly to me. I would like this image gallery to sit behind everything else. right now white shows through on either side. Any help would be greatly appreciated. Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="Generator" content="Get Hosting With Joe (13.0.1.020)"> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> <title>Home</title> <script type="text/javascript" src="wpscripts/jquery.js"></script> <script type="text/javascript" src="wpscripts/jquery.timers.js"></script> <script type="text/javascript" src="wpscripts/jquery.wpgallery.js"></script> <script type="text/javascript"> var nImgNum_pg_2 = 0; wp_imgArray_pg_2 = new Array(); wp_imgArray_pg_2[nImgNum_pg_2++] = new wp_galleryimage("wpimages/6ec6f779d991.jpg", 844, 369, "wpimages/6ec6f779d991t.jpg", ""); wp_imgArray_pg_2[nImgNum_pg_2++] = new wp_galleryimage("wpimages/8dcdb90c2d41.jpg", 844, 370, "wpimages/8dcdb90c2d41t.jpg", ""); </script> <style type="text/css"> body {margin: 0px; padding: 0px;} </style> <script type="text/javascript" src="wpscripts/jspngfix.js"></script> <script type="text/javascript"> var blankSrc = "wpscripts/blank.gif"; </script> <script type="text/javascript"> $(document).ready(function() { $('#wp_gallery_pg_2').wpgallery({ imageArray: wp_imgArray_pg_2, nTotalImages: nImgNum_pg_2, nGalleryLeft: 77, nGalleryTop: -183, nGalleryWidth: 844, nGalleryHeight: 842, nImageDivLeft: 0, nImageDivTop: 0, nImageDivWidth: 844, nImageDivHeight: 842, nControlBarStyle: 0, nControlBarExternalTop: 10, bNavBarOnTop: false, bShowNavBar: false, nNavBarAlignment: 0, strNavBarColour: 'none', nNavBarOpacity: 1.0, nNavBarIconWidth: 24, nNavBarIconHeight: 24, bShowCaption: false, bCaptionCount: true, strCaptionColour: '#ffffff', nCaptionOpacity: 0.6, strCaptionTextColour: '#000000', nCaptionFontSize: 12, strCaptionFontType: 'Courier New,Arial,_sans', strCaptionAlign: 'center', strCaptionFontWeight: 'normal', bShowThumbnails: false, nThumbStyle: 1, nThumbPosition: 0, nThumbLeft: 30, nThumbTop: 732, nThumbOpacity: 0.5, nTotalThumbs: 2, nThumbSize: 40, nThumbSpacing: 10, bThumbBorder: false, strThumbBorderColour: '#000000', strThumbBorderHoverColour: '#ffffff', strThumbBorderActiveColour: '#ffffff', bShowThumbnailArrows: false, nThumbButtonSize: 24, nThumbButtonIndent: 50, nColBorderWidth: 2, nTransitionStyle: 1, nStaticTime: 3044, nTransitTime: 1015, bAutoplay: true, loadingButtonSize: 38, bPageCentred: true, nPageWidth: 1000, nZIndex: 100, loadingButtonSrc: 'wpimages/wpgallery_loading_1.gif', blankSrc: 'wpscripts/blank.gif', rewindButtonSrc: 'wpimages/wpgallery_rewind_0.png', prevButtonSrc: 'wpimages/wpgallery_previous_0.png', playButtonSrc: 'wpimages/wpgallery_play_0.png', pauseButtonSrc: 'wpimages/wpgallery_pause_0.png', nextButtonSrc: 'wpimages/wpgallery_next_0.png', forwardButtonSrc: 'wpimages/wpgallery_forward_0.png', thumbRewindButtonSrc: 'wpimages/wpgallery_rewind_0.png', thumbForwardButtonSrc: 'wpimages/wpgallery_forward_0.png', rewindoverButtonSrc: 'wpimages/wpgallery_rewind_over_0.png', prevoverButtonSrc: 'wpimages/wpgallery_previous_over_0.png', playoverButtonSrc: 'wpimages/wpgallery_play_over_0.png', pauseoverButtonSrc: 'wpimages/wpgallery_pause_over_0.png', nextoverButtonSrc: 'wpimages/wpgallery_next_over_0.png', forwardoverButtonSrc: 'wpimages/wpgallery_forward_over_0.png', thumboverRewindButtonSrc: 'wpimages/wpgallery_rewind_over_0.png', thumboverForwardButtonSrc: 'wpimages/wpgallery_forward_over_0.png', strRewindToolTip: 'Reverse', strPreviousToolTip: 'Previous', strPlayToolTip: 'Play', strPauseToolTip: 'Pause', strNextToolTip: 'Next', strForwardToolTip: 'Forward', strThumbRewindToolTip: 'Reverse', strThumbForwardToolTip: 'Forward' }); }) </script> </head> <body text="#000000" style="background-color:#ffffff; text-align:center; height:1200px;"> <div style="background-color:transparent;text-align:left;margin-left:auto;margin-right:auto;position:relative;width:1000px;height:1200px;"> <div id="wp_gallery_pg_2" style="position:absolute; left:77px; top:-183px; width:844px; height:842px; overflow:hidden;"></div> <img src="wpimages/wp7d3e6c5d_06.png" width="997" height="1197" border="0" alt="" onload="OnLoadPngFix()" style="position:absolute;left:0px;top:3px;"> </div> </body> </html> 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? IE, Chrome, and Safari all display this page correctly: http://eataustineat.com/testfolder2/ here is what i mean by Firefox displays it incorrectly in firefox: 1) type 'f' into the search field 2) you should move over to a youtube video 3) now click the Search tab at the bottom 4) you should notice the a portion of the video remains visable. the site uses jquery for the slider. what should I be looking for? 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\">"; } ?> I thought this would be simple. Evidently it's not With the date below (and it being 11.45 on the 27th as I type this), the counter returns the correct number of hours/mins/seconds remaining, but shows 33 days. It seems to be adding 31 days to the count, but I can't figure out where Code: function countdown(){ var bigday = new Date(2009,10,29,14,30,0,0); var today = new Date(); var difference = bigday - today; var remaining = Math.floor(difference/1000); // want seconds, not milliseconds var days = Math.floor(remaining/86400); remaining = remaining % 86400; var hours = Math.floor(remaining/3600); remaining = remaining % 3600; var minutes = Math.floor(remaining/60); remaining = remaining % 60; seconds = Math.floor(remaining); var out = days + " days, " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds left..."; $('#countdown').text(out); setTimeout(countdown, 1000); } 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 am working with using Javascript to create a page that scales and keeps its aspect ratio (much like a Flash page would). After a lot of trial and error, I have a prototype up with a couple of problems. It loads correctly once in I.E. Reloading, or opening a new browser, will also load the page correctly. But visiting a different page and coming back causes the width attributes to break. This happens with the non-aspect-ratio version in pure HTML also, but I was hoping that this problem would be solved by establishing values based on javascript variables. As for Firefox, the problem is more or less exactly the opposite. The page loads up all wonky the first time, and a reload or resize will fix it for every time afterward. To see what I'm talking about, you can take a look at http://www.jonesmfgmusic.com/testpag...lem_width.html For the HTML only version, see http://www.jonesmfgmusic.com/testpag...blem_html.html I'm guessing this is something to do with the order in which the data is loaded, so that once the information is all cached, it stops functioning in IE, and starts functioning in FF... can anyone confirm whether I'm on the right track with that, or how to fix it if I am? I'm most concerned by the fact that the width attribute is behaving as it does in IE. That looks like some kind of Microsoft bug to me, and I need a way around it. As for Firefox, I am guessing if I can just get it to load all of the correct information ahead of time, the page should come up correctly, but I just can't think how to do that. i'm doing the following on a select box to load the next select box (in a td with the id) if I look at the html returned by the ajax call I get PHP Code: <select name=optionvalue /><option value='test 1'>test 1</option><option value='test 2'>test 2</option><option value='test 3'>test 3</option></select> but it's showing as the select box and then test 1test 2test 3 my javascript code is PHP Code: function Loadoptionvalueselect() { //alert("here"); urltoajax = "getoptionsvaluesselect.asp?1=1" strarea = document.getElementById('optionid').value; urltoajax = urltoajax + '&optionid=' + strarea urltoajax = urltoajax + '&rnd=' + Math.round(Math.random() * 10000) // alert(urltoajax); $.ajax({ url: urltoajax, cache: false, success: function(html) { $("#troptionvalue").html(html); } }); } any ideas what could be causing this? I am returning the present time - then using the .substr to remove all digits except the last two on the right (i.e effectively returning the value 32 from 65344532) I am then looping, subtracting 11 from that number until the value is less than 11. The intent being to then return the value from the appropriate matching array ID I have an array sl1 sl1[0]; sl1[1]; sl1[2]; sl1[3]; sl1[4]; sl1[5]; sl1[6]; sl1[7]; sl1[8]; sl1[9]; sl1[10]; The problem arises with evaluating two digit numbers beginning with zero - In cases where the last two numbers are greater than 09, the looping returns a 1 digit number for valuse less than 10, in cases where the last two digits begin with zero the loop will not begin. I have attempted to use the switch(n) to determine if any 01, 02, 03 ... etc exists but this is not evaluating correctly - is this due to using the date/time object and if so is there a good way to convert this to either a numeric or string datatype where the case can be evaluated correctly? Thanks in advance! -------- Hi I have a problem with the javascript menu. Currently when you click on the "Login" button then it opens and when you click it again while it is open it closes ands opens again. What I want is when you click the login button while it is open then it closes as toggleable button. I have posted the javascript to this page: http://jsbin.com/uhefoc/edit#javascript,html,live So there it is possible to make realtime updates to the script and see the result real time I also posted the script here so not to break the rules: Code: $(document).ready(function() { $("#login-menu a.signin").click(function(event) { var link = $(this), box = $("fieldset#signin_menu"), inputs = $("#signin_menu .form-input input"); event.preventDefault(); link.toggleClass("menu-open"); box.toggle("signin_menu"); if(link.hasClass("menu-open")) { $("#username").focus(); } else { inputs.val(''); } inputs.bind("focus keydown", function(action) { if((action.type == "keydown" && action.keyCode == 27) || (action.type == "focus" && !link.hasClass("menu-open")) ) { link.trigger("click"); } }); box.mouseup(function () { return false; }); $(document).mouseup(function(what) { if($(what.target).parent("a.signin").length == 0 && link.hasClass("menu-open")) { link.trigger("click"); } }); }); }); I'm a js noob but have managed to cobble together some code for a simple calculator. All the math works well, but changing the radio button doesn't have any effect. Basically, I have 4 set of equations (long if/then statements) - 2 are to be used when one radio button is checked, 2 if the other is checked. Code: <html><head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <script language="JavaScript"> function temp(form) { var r1 = form.r1.value; var GNW = parseFloat(form.GNW.value, 10); var BNW = parseFloat(form.BNW.value, 10); var totalfee = 0; var netfee = 0; var discount = 0; //if the "old" radio button is selected, use the the next two if/then formulas if (r1=1) { for brevity sake, I'll omit the first two if/then equations Code: //close out the "old" options } //use the "new" option else if (r1=2) { // two more if/then statements } // this applies to all conditions discount = totalfee - netfee; form.totalfee.value = totalfee/4; form.netfee.value = netfee/4; form.discount.value = discount/4; } and now the radio buttons Code: <input name="r1" value=1 type="radio" checked="checked">Old (3m/3m) <input name="r1" value=2 type="radio" >Current (5m/5m)</p><p> hopefully the brevity makes the answer apparent, the full code is attached if I've left out a crucial detail. 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> 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> 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 I 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> Hiya, I'm looking for some guidance on a part of some coding practice I'm stuck on! I've created a shopping cart using javascript, the items save to the arrays etc and it all works fine. If the user adds the same product again to the cart the quantity is added onto the previous quantity that is already in the cart. To check if the item is already in the cart I've ued the below code, but what it does is update the quantity for the first cart, and when it updates the quantity for the second item it updates the quantity but keeps adding the same product to the cart in seperate elements of the array as well (if that makes sense? here are the two functions used: Code: function additem(id) { itemName = document.getElementById('name' + id).innerHTML; itemQuantity = parseInt(document.getElementById('quantity' + id).value); itemPrice = parseFloat(document.getElementById('price' + id).innerHTML); if(numitems == 0){ items[++numitems] = new Item(itemName,itemPrice,itemQuantity); displaycart(); } else{ checkarray(id, itemName, itemQuantity, itemPrice); } } function checkarray(id, itemName, itemQuantity, itemPrice){ for(i=1;i<=numitems;i++) { if(items[i].name == itemName){ items[i].quantity += parseInt(document.getElementById('quantity' + id).value); displaycart(); return true; } items[++numitems] = new Item(itemName,itemPrice,itemQuantity); } } It may jsut be a simple mistake I've made but it's been bugging me a lot and I can't seem to fix it, any help/pointers would be greatly appreciated. Hi, I have a question here. I have 2 videos and if I click the image which uses #usemap, it will switch to the specific videos I clicked. FF and chrome has no problem but only IE. The scenario is like this: Actual scenario is when the page load, it will display tab 1, video 1 and tab 2 is greyed out. If I clicked on tab 2, tab 1 is greyed out and video 2 is display. Both tabs I use #usemap. But now the problem in IE is that it keeps on displaying tab 1 and video 2 instead of video 1 and when I clicked tab 2, tab 2 is selected but no video is loaded. Below is a simple code which hope it can helps better understanding of what I'm trying to do: Code: <div> <img src="tab.jpg" id="tab1" #usemap="videotab"> <img src="tab.jpg" id="tab2" #usemap="videotab"> </div> <div id="video1" style="display:block"><"1st video source codes here"></div> <div id="video2" style="display:none"><"2nd video source codes here"></div> <map name="videotab"> <area href="" onclick="swapvideo(1); return false;" /> <area href="" onclick="swapvideo(2); return false;" /> </map> function swapvideo(num){ if (num == 1) { document.getElementById("video1").style.display = "block"; document.getElementById("video2").style.display = "none"; document.getElementById("tab1").style.display = "block"; document.getElementById("tab2").style.display = "none"; } else if (num == 2) { document.getElementById("video2").style.display = "block"; document.getElementById("video1").style.display = "none"; document.getElementById("tab2").style.display = "block"; document.getElementById("tab1").style.display = "none"; } } This is the brief code. IE just keep displaying video 2 when page load and video doesn't loads when tab 2 is clicked. Even if I program the 2 divs to be show, it only shows video 2 and video 1 is nowhere to be seen. And I tried taking out the video 2 codes, video 1 then can be seen. Hope you guys out there can understand what I'm trying to say. |