JavaScript - Us Telephone Number Validation Fails
Hello,
I have the following code that, among other things, should validate US telephone numbers with format: "(800) 800-8000" with hyphen, parenthesis and spaces optional. The regexp is: /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/ My main problem is that it validates also numbers like 800 or 800000000000000 etc. The code works perfectly on test pages but not on my website. Something similar happens also for the zipcode. Can someone please tell me what could be wrong? Thanks! Code: (function($){ $.fn.ax_validate = function(f){ stopAnim(); // just too much otherwise //console.log(typeof f + ', id = ' + f.id); var n, el, err = [], msg = [], fmats = { 'email': /^[\w\.\-]+\x40[\w\.\-]+\.\w{2,4}$/, 'phone': /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/, 'zip': /^\d{5}(-\d{4})?$|[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d/ }; $('input[type=text],textarea').each(function(i){ $(this).val( $.trim($(this).val()) ); }); $('label.req').each(function(i){ n = $(this).attr('for'); el = $('input[name=' + n + ']'); if (typeof fmats[n] != 'undefined' && !el.val().match(fmats[n])) { err.push(n); msg.push($(this).text() + ((el.val() == '') ? '' : ' (invalid format)')); $(this).animate({color: '#A60'}, 1000); } else if (el.val() == '') { err.push(n); msg.push($(this).text()); $(this).animate({color: '#A00'}, 1000); } else { $(this).css('color', '#0f4068'); } }); if (err.length == 0) { //alert('All ok!'); //f.submit(); return true; } alert('<b>Please fix the following required fields:</b><br /><br />' + msg.join('<br />')); //$('input[name=' + err[0] + ']').focus(); return false; }; })(jQuery); Similar TutorialsHello All, I am not too good with javascript so I apologise in advance! I have a website form where people input their contact details and I need a script which allows the form to be submitted if the telephone number is correct and returns an error if the number is invalid, (preferably in a pop-up box - not on another page) which says something like "The telephone number you have entered is invalid. Please enter a valid UK landline or mobile number". For the number to be valid, it has to either start with an "01", an "02" or an "07" and be either 10, or 11 digits long. The user should also be able to enter space without an error (ie, the script should ignore spaces). Any suggestions would be much appreciated. Regards, AC So, I know there are lots of threads out there about the jQuery validation plugin and people having issues with IE7, but most of them come down to syntax issues with a closing comma or what not. With that said, I have milled over this code of least a full day now and still have no idea why it fails in IE (all versions) http://jsfiddle.net/rM3ej/4/ Can anyone give me some ideas or insight why this would completely fail? Thanks in advanced. http://edison.seattlecentral.edu/~dw.../testform2.htm http://edison.seattlecentral.edu/~dw...ude/util-dw.js Could someone check js and tell me how I can get the form to validate it hangs up on password. Hi there, I need to validate three textboxes and it will validate for numbers. How should I change my code to validate three textboxes? Code: <!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>Untitled Page</title> <script type='text/javascript' language="javascript"> var validPhoneChar = "+"; // Minimum no of digits in an international phone no. var minDigitsInPhoneNumber = 10; function isInteger(s) { var i; for (i = 0; i < s.length; i++) { // Check that current character is a number. var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; } // All characters are numbers. return true; } function stripCharsInBag(s, bag) { var i; var returnString = ""; // Search through string's characters one by one. // If character is not in bag, append to returnString. for (i = 0; i < s.length; i++) { // Check that current character isn't whitespace. var c = s.charAt(i); if (bag.indexOf(c) == -1) returnString += c; } return returnString; } function checkRequirements(strPhone) { if(strPhone.indexOf("+") > 1) return false; s = stripCharsInBag(strPhone,validPhoneChar); return (isInteger(s) && s.length >= minDigitsInPhoneNumber); } function ValidateForm() { var Phone = document.getElementById("Text1"); //var Phone1 = document.getElementById("Text23"); if ((Phone.value == null)||(Phone.value == "")) //if match failed { alert("Please Enter your Phone Number."); Phone.focus(); return false; } /*if ((Phone1.value == null)||(Phone1.value == "")) //if match failed { alert("Please Enter your Phone Number0."); Phone.focus(); return false; }*/ if (checkRequirements(Phone.value) == false) { alert("Please Enter a Valid Phone Number."); Phone.value = ""; Phone.focus(); return false; } else alert("YAY!"); return true; } function NotAllowSpace() { // Get the ASCII value of the key that the user entered var key = window.event.keyCode; // Verify if the key entered was a Space if ( key == 32 ) { // If it was, then dispose the key and continue with entry window.event.returnValue = null; alert("Invalid,Please check") } else // If it was not, then allow the entry to continue return; } </script> </head> <body> <label>Office Telephone:</label> <input id="Text1" type="text" onkeydown = "return (event.keyCode != 32)"/><br /> <input id="Button1" type="button" value="button" onclick="return ValidateForm();" /><br /> </body> </html> I need to use Javascript to validate 3 textboxes, whereby the users can only key in numbers (because they are phone numbers related fields). If any of the textbox is empty, display an alert message to show which textbox is empty. I do not want to show many alert messages to show that, for example, text1 and text2 are empty, it will show two alert messages. I would need to show one "summarized" alert message instead. Next, check if the textbox matches the pattern (which is to check if it has the skeleton of a phone number). If it is, show an alert message that it is alright. Else, show that it does not match. Need Phone Number Validation for my JavaScript, i can't work it out It currently has E-mail, Surname, Address and Name validation, This is my code at the moment: Code: <script language="JavaScript"> function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(at,(lat+1))!=-1){ alert("Please Enter a Valid E-mail") return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(dot,(lat+2))==-1){ alert("Please Enter a Valid E-mail") return false } if (str.indexOf(" ")!=-1){ alert("Please Enter a Valid E-mail") return false } return true } function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } function validate_form(thisform) { with (thisform) { if (validate_required(Name,"Name must be filled out!")==false) {Name.focus();return false;} if (validate_required(Surname,"Surname must be filled out!")==false) {Surname.focus();return false;} if (validate_required(Country,"Address must be filled out!")==false) {Country.focus();return false;} } { var emailID=document.submitting.email if ((emailID.value==null)||(emailID.value=="")){ alert("Please Enter a Valid E-mail") emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" emailID.focus() return false } return true } } function verifyEmail(form) { checkEmail = form.email.value if ((checkEmail.indexOf('@') < 0) || ((checkEmail.charAt(checkEmail.length-4) != '.') && (checkEmail.charAt(checkEmail.length-3) != '.'))) {alert("You have entered an invalid email address. Please try again."); form.email.select(); return false; } else { form.method="get"; form.rel="nofollow" target="_self"; form.action="myscript.cgi"; form.submit(); } } </script> Code: <form action="submit.htm" onsubmit="return validate_form(this)" method="post" name="submitting"> <span class="style5">Select Plant: <form id="form1" name="form1" method="post" action=""> <label> <select name="Item" id="Item"> <option>OMGwoopwoop Plant</option> <option>I'm Blue Plant </option> <option>Anonymous Plant</option> <option>Rawr Plant</option> <option>Chicka Plant </option> <option>Fruitopola Plant</option> <option>Whitoe Plant</option> <option>Wukidoo Plant </option> </select> </label> </p> <p>Name:<span class="style1"> <input type="text" name="Name" size="30"> <br> <br> </span>Surname: <span class="style1"> <input type="text" name="Surname" size="30"> <br> <br> </span>Address:<span class="style1"> <input type="text" name="Country" size="30"> <br> <br> </span>Email:<span class="style1"> <input type="text" name="email" size="30"> <br></span></p> Phone Number:<span class="style1"> <input type="text" name="phone" size="30"> <form action="submit.htm" onSubmit="return validate_form(this)" method="post"> <input type="submit" value="Submit"> </form> Hi guys, I have written a double validation as below function validateDouble(ele){ // Custom trim funcation, i have written if(trim(ele.value) != ''){ var a = /^\d+(\.\d{0,2})?$/.test(trim(ele.value)); if(a){ return true; }else{ return false; } }else { ele.value = '0.00'; return true; } } I have copied from the net But this validation doesnt work when we enter the value as .65 (Means, it should accept this also, Please help me to change the regular expression) and in the same time when we enter this with out prefix, it should auto change to 0.65. Can some one help me to add in the above function. Hi! I wish to know if one can dynamically validate a textbox that accepts telephone numbers. I plan to do this by: first selecting a country form a dropdown box. then validate the text box for the corresponding country selected... but do not have any idea how to do it! can you help me ? I have a phone number field on my form that needs validation, but I'm not sure how to code this. I have the following function to validate a first name is entered and last name. The phone number field must match a 7 digit or 10 digit(with area code)phone number. I want to be able to include paranthese and/or hyphens for the valid phone number. function checkForm1() { if (document.forms[0].firstname.value.length == 0) { alert("You must put in a first name"); return false; } else if (document.forms[0].lastname.value.length == 0) { alert("You must put in a last name"); return false; } I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
When I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? Here is the PHP: PHP Code: <?php if (($totalRows_getDie = mysql_num_rows($getDie)) != NULL) { echo "Die Category: <select name='DieCatId' class='dropMenu' id='DieCatId' onchange='jobDieChange(this.value)'> <option value='NULL'></option>"; do { echo "<option value='".$row_dieCatList['DieCatID']."'"; if (!(strcmp($row_dieCatList['DieCatID'], $row_getDie['DieCatID']))) {echo "selected=\"selected\"";} echo ">".$row_dieCatList['DieCatDesc']."</option>"; } while ($row_dieCatList = mysql_fetch_assoc($dieCatList)); $rows = mysql_num_rows($dieCatList); if($rows > 0) { mysql_data_seek($dieCatList, 0); $row_dieCatList = mysql_fetch_assoc($dieCatList); } echo "</select> <a href='popup.php?getpage=dieins' onclick='window.open(this.href, 'popupwindow', 'width=770,height=675,scrollbars,resizable'); return false;'>Add Die</a><br />"; echo "Die: <select name='DieID' class='dropMenu' id='DieID'>"; if ($totalRows_getDie != 0) { echo "<option value='".$row_getDie['DieID']."'>".$row_getDie['DieDesc']."</option>"; } echo "</select><br />"; echo "<input type='hidden' name='DiecutID' value='".$row_getDie['DiecutID']."' />"; } ?> And the JS: Code: var xmlhttpJDie; function jobDieChange(str) { xmlhttpJDie=GetXmlHttpObject(); if (xmlhttpJDie==null) { alert ("Browser does not support HTTP Request"); return; } var url="/scripts/jobdie.php"; url=url+"?q="+str; url=url+"&sid="+Math.random(); xmlhttpJDie.onreadystatechange=JobDieGet; xmlhttpJDie.open("GET",url,true); xmlhttpJDie.send(null); } function JobDieGet() { if (xmlhttpJDie.readyState==4) { document.getElementById("DieID").innerHTML=xmlhttpJDie.responseText; } } In all browsers except IE, it works fine, but IE gets a Script error and won't update the second select. I've gone over this so many times I'm cross eyed! If someone could please help me figure out why IE doesn't like this I would appreciate it. Thank you! I have a form that is used to insert a new classified ad or to update an existing ad. When the submit button is pressed a javascript function is called to validate the fields. Some of the fields are set as required. If the field is empty ( as form[i].value = '' ) then this sets an error flag and after all fields have been tested will display an alert and each field that has an error will be highlighted in red. This works great when a new ad is being created, but when the ad is being updated, and a required field is erased then it doesn't popup as an error, as if the script is just ignoring it. Here is the code snipit: Code: function submitbutton(mfrm) { var me = mfrm.elements; var r = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-]", "i"); var r_num = new RegExp("[^0-9\.,]", "i"); var r_email = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,3}$" ,"i"); var errorMSG = ''; var iserror=0; // set notification background color var warnColor = '#<?php echo $this->error_color; ?>'; // loop through all input elements in form for (var i=0; i < me.length; i++) { // check if element is mandatory; here mosReq="1" if ((me[i].getAttribute('mosReq') == 1)&&(me[i].style.visibility != 'hidden')) { if (me[i].type == 'radio' || me[i].type == 'checkbox') { var rOptions = me[me[i].getAttribute('name')]; var rChecked = 0; if(rOptions.length > 1) { for (var r=0; r < rOptions.length; r++) { if (rOptions[r].checked) { rChecked=1; } } } else { if (me[i].checked) { rChecked=1; } } if(rChecked==0) { errorMSG += me[i].getAttribute('mosLabel').replace(' ',' ') + ' : <?php echo html_entity_decode(addslashes(JText::_('COM_CLASSIFIEDSREDUX_REGWARN_ERROR')),ENT_QUOTES); ?>\n'; // notify user by changing background color, in this case to red me[i].style.background = warnColor; iserror=1; } } if ((me[i].value == '') || (me[i].value.length < 2)) { errorMSG += me[i].getAttribute('mosLabel').replace(' ',' ') + ' : <?php echo html_entity_decode(addslashes(JText::_('COM_CLASSIFIEDSREDUX_REGWARN_ERROR')),ENT_QUOTES); ?>\n'; me[i].style.background = warnColor; iserror=1; } } } if(iserror==1) { alert(errorMSG); return false; } } This is the code part that fails it's if check. Code: while (n<=30) { var slot='#slot'+n; $( slot ).data({no: n, id: itemId[i], name: itemName[i], equip: itemEquip[i], lvl: itemLvl[i], bonus: itemBonus[i], rstr: itemRStr[i], rdef: itemRDef[i]}); $( slot ).draggable({ handle: slot, stack: slot, revert: "invalid", snap: "div#"+itemEquip[i], snapMode: 'inner', start: function(event, ui) { $('div#'+$(this).data('equip')).css({'border': '2px dashed #0066CC', 'background': 'rgba(255,255,255,0.2)'}) .droppable ({ drop: function(event, ui) { if (pLvl>=$('.ui-draggable-dragging').data('lvl') && pStr>=$('.ui-draggable-dragging').data('rstr')) { alert(pLvl+", "+$('.ui-draggable-dragging').data('lvl')); $('.ui-draggable-dragging').css({'display':'none'}); $('div#'+$('.ui-draggable-dragging').data('equip')).html ( "<img src='items/equipped/"+$('.ui-draggable-dragging').data('name')+$('.ui-draggable-dragging').data('id')+".png' />" ) $.ajax({type:"GET", url:"items/change.php", data:"id="+$('.ui-draggable-dragging').data('id')+"&no="+$('.ui-draggable-dragging').data('no'), cache:false, timeout:5000, error: function() { $('div.nogood').html ( "There was an error. Please inform us about it in the forum." ).css({'width':'400px','margin-left':'-200px'}); $( 'div.nogood' ).fadeIn(500, away); function away() { $( 'div.nogood' ).delay(2000).fadeOut(500); }; } }); } else { alert("HUh"); $( 'div.nogood' ).fadeIn(500, away).css({'width':'400px','margin-left':'-200px'});; $('.ui-draggable-dragging').draggable({revert: true}); if (pLvl<$('.ui-draggable-dragging').data('lvl')) { alert("Good"); } else if (pStr<$('.ui-draggable-dragging').data('rstr')) { $('div.nogood').html("Not enough strength.") } function away() { $( 'div.nogood' ).delay(1400).fadeOut(500); }; } } }); }, stop: function(event, ui) { $('div#'+$(this).data('equip')).css({'border':'none', 'background':'transparent'}).droppable("destroy"); } }); n++; i++; } This if comparison if (pLvl>=$('.ui-draggable-dragging').data('lvl') && pStr>=$('.ui-draggable-dragging').data('rstr')) somehow goes through. After the if statement I check the values with the alert but it displays 5 for pLvl and 10 for the draggables data (which are the correct numbers) so can anyone tell me why does this if statement still go through when pLvl is lower? Hi, does 'focus' method show a 'stable' result? i call this method on a node -- if this one is not absolutely positioned -- it seems nothing happens so ① does this method only apply to absolutely positioned element? also, in FF, aNode.focus() has no effect whereas in IE document will scroll until that node is visible if the node is partially invisible at the bottom. ②is this a bug in FF? here is the code Code: <div style="position:absolute; left:50px; top: 700px" onclick="this.focus();"> yepsfagadgre<br />agefderdsf<br />agefderdsf<br />agefderdsf</div> scroll the document until the text is half-visible at the bottom. click on it -- in IE it will scroll up while in FF nothing happens besides, if it is not absolutely positioned, nothing happens either~~~ thx in advance I cant figure out why this doesnt work - Firefox says: Error: document.getElementById("test") is null Source File: file:///Users/briantoovey/test.html Line: 10 Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>Rotating Quotes</title> </head> <body> <script type="text/javascript"> document.getElementById("test").innerHTML = 'eat it'; </script> <div id="test"></div> </body> </html> I have a function called onload that includes this: Code: window.onload=new function(){ ... if (menuletter!=false){ document.cookie="hddrv="+(menuletter)+"; path=/; expires="+exp.toGMTString(); document.enterIndex.src='enter2.gif'; // window.setTimeout("goIndex()",7000); // return false; } ... } <img border="0" name="enterIndex" src="enter1.gif" width="413" height="41"> If I uncomment the two lines and comment the document image swap line, they execute perfectly, so the routine works. But if I try to do the image swap instead of the two commented lines, it doesn't swap. Of course, the image enter1.gif and enter2.gif exist. What am I doing wrong? I have a form that passes values to a next step. It has two sub divs that show depending on what's selected from the dropdowns in the top two divs. I'm trying to keep the selected sub divs open if the user hits previous step. The divs stay open in FF but not in IE. Any ideas? dropdowns Code: <table border="0" cellspacing="0" cellpadding="2"> <tr valign="top"> <td align="right">Morning:</td> <td><select name="wcsave_10_msession" id="wcsave_10_msession" size="1" onblur="CheckField(this.form,this,'');" onchange="display1(this,'Concurrent sessions 1-6');"> <option value="" selected="selected">Choose one</option> <option value="Mastery session 1 - Computer Lab: Searching Essentials"> <strong>Mastery session 1</strong> - Computer Lab: Searching Essentials</option> <option value="Concurrent sessions 1-6">Concurrent sessions 1-6</option> </select> </td> </tr> <tr valign="top"> <td> </td> <td> <div id="Concurrent sessions 1-6" style="display: none;"> <table class="special"> <tr valign="top"> <td>Choose a session for each time slot.<br /> (9:15 a.m. - 10:15 a.m.)<br /><select name="wcsave_10_session_mconc1" id="wcsave_10_session_mconc1"> <option value="" selected="selected">Choose one</option> <option value="Concurrent session 1 - IRB 101 for Research Nurses">Concurrent session 1 - IRB 101 for Research Nurses</option> <option value="Concurrent session 2 - A Research Poster Contest as a Tool to Learn About Research/EBP">Concurrent session 2 - A Research Poster Contest as a Tool to Learn About Research/EBP</option> <option value="Concurrent session 3 - Beginning the EBP Journey: Evaluating and Synthesizing the Literature">Concurrent session 3 - Beginning the EBP Journey: Evaluating and Synthesizing the Literature</option> </select> </td> </tr> <tr valign="top"> <td>(10:30 a.m. - 11:30 a.m.)<br /><select name="wcsave_10_session_mconc2" id="wcsave_10_session_mconc2"> <option value="" selected="selected">Choose one</option> <option value="Concurrent session 4 - Making Sense of Statistics When Reading Research">Concurrent session 4 - Making Sense of Statistics When Reading Research</option> <option value="Concurrent session 5 - Original Research Presentations">Concurrent session 5 - <em>Original Research Presentations</em></option> <option value="Concurrent session 6 - IRB Considerations with Vulnerable Populations">Concurrent session 6 - IRB Considerations with Vulnerable Populations</option> </select> </td> </tr> </table> </div> </td> </tr> <tr valign="top"> <td colspan="2"> </td> </tr> <tr valign="top"> <td align="right">Afternoon:</td> <td><select name="wcsave_10_asession" id="wcsave_10_asession" size="1" onblur="CheckField(this.form,this,'');" onchange="display2(this,'Concurrent sessions 7-12');"><!--showDiv(this.value)--> <option value="" selected="selected">Choose one</option> <option value="Mastery session 2 - Beyond the Basics of Searching!"><strong>Mastery session 2</strong> - Beyond the Basics of Searching!</option> <option value="Concurrent sessions 7-12">Concurrent sessions 7-12</option> </select> </td> </tr> <tr valign="top"> <td> </td> <td> <div id="Concurrent sessions 7-12" class="hiddenDiv"> <table class="special"> <tr valign="top"> <td>Choose a session for each time slot.<br /> (1:45 p.m. - 2:45 p.m.)<br /><select name="wcsave_10_session_aconc1" id="wcsave_10_session_aconc1"> <option value="" selected="selected">Choose one</option> <option value="" selected="selected">Choose one</option> <option value="Concurrent session 7 - EBP Protocols">Concurrent session 7 - EBP Protocols</option> <option value="Concurrent session 8 - Writing for Publication">Concurrent session 8 - Writing for Publication</option> <option value="Concurrent session 9 - Original Research Presentations">Concurrent session 9 - Original Research Presentations</option> </select> </td> </tr> <tr valign="top"> <td>(3:00 p.m. - 4:00 p.m.)<br /><select name="wcsave_10_session_aconc2" id="wcsave_10_session_aconc2"> <option value="" selected="selected">Choose one</option> <option value="Concurrent session 10 - Writing a Research Question Using PICO">Concurrent session 10 - Writing a Research Question Using PICO</option> <option value="Concurrent session 11 - EBP Project Presentations">Concurrent session 11 - EBP Project Presentations</option> <option value="Concurrent session 12 - The Role of the Research Facilitator">Concurrent session 12 - The Role of the Research Facilitators</option> </select> </td> </tr> </table> </div> </td> </tr> </table> javascript: Code: var lastDiv = ""; function showDiv(divName) { var items = document.getElementById('wc_addItem_ADV'); var form = document.getElementById('webcredit'); var total = document.getElementById('Total'); var amount = document.getElementById('amount'); // set checkboxes to 0 for (var i = 0; i < form.elements.length; i++ ) { if (form.elements[i].type == 'checkbox') { form.elements[i].checked = false; document.getElementById(form.elements[i].id).value = "0"; } } total.value = ''; amount.value= ''; // hide last div if (lastDiv) {document.getElementById(lastDiv).className = "hiddenDiv";} //if value of the box is not nothing and an object with that name exists, then change the class if (divName && document.getElementById(divName)) { document.getElementById(divName).className = "visibleDiv"; lastDiv = divName; } } function showInitialDiv() { var selBox = document.getElementById('wcsave_10_session_mconc1'); if (selBox == undefined || selBox == null) return; var val = selBox.options[selBox.selectedIndex].value; if (val == null || val == '') return; showDiv(val); } I only call one of the sub div ID's but it seems to work in FF with no errors. Everything is called with: Code: <body onload="showInitialDiv();"> i cant get collission detection to work. i tryed but it always caused an infinite loop. heres the code. Code: <html> <!-- main file.--> <head> <title>lightning generator</title> </head> <body> <canvas id='world' width='500' height='500' style='border: 1px solid black; padding:0;'></canvas> <script type="text/javascript" src='world.js'></script> <script type='text/javascript' src='eC.js'></script> <script type='text/javascript' src='world.ground.js'></script> <script type='text/javascript'> world.bolt = { } ; world.bolt.paths = []; // main obj inits world.bolt.draw = function(){ var x, y; for( var id = 0; id <= world.bolt.draw.num; id ++ ){ world.ctx.moveTo( world.bolt.paths[id].x[world.bolt.paths[id].x.length-1], world.bolt.paths[id].y[world.bolt.paths[id].y.length-1] ); var mdx=Math.floor(Math.random()*world.bolt.paths[id].mdx); x = world.bolt.paths[id].x[world.bolt.paths[id].iters] + ((Math.random()<Math.random())?mdx:-mdx); y = ++ world.bolt.paths[id].iters; world.bolt.paths[id].x.push( x ); world.bolt.paths[id].y.push( y ); world.ctx.strokeStyle = world.bolt.paths[id].color; world.ctx.lineTo( x, y ); world.ctx.stroke(); //world.ctx.beginPath(); } if(x%3==0){ world.ctx.fillStyle=world.skyColor; world.ctx.fillRect(0,0,world.w,world.h);} } world.bolt.draw.num=-1; world.bolt.cpath = function( x, y, mdx, srate, id, color ){ world.bolt.paths[id] = { } ; world.bolt.paths[id].iters = 0; world.bolt.paths[id].x = []; world.bolt.paths[id].y = []; world.bolt.paths[id].x[0] = x; world.bolt.paths[id].y[0] = y; world.bolt.paths[id].mdx = mdx; world.bolt.paths[id].srate = srate; world.bolt.paths[id].color = color; world.bolt.draw.num += 1; } world.bolt.cpath(250,0, 5,5,0,'rgba(255,255,150,.5)'); window.setInterval(world.bolt.draw,100) window.setTimeout('world.bolt.cpath(125,0,5,5,1,"rgba(255,10,0,.5)")',1000); </script> </body> </html> Code: //world.js var world = { skyColor:'rgba(0,0,100,.009)' } ; world.canvas = document.getElementById( 'world' ) world.canvas.cstyle = document.defaultView.getComputedStyle( world.canvas, null ) world.w = parseInt( world.canvas.cstyle.width, 10 ); world.h = parseInt( world.canvas.cstyle.height, 10 ); world.ctx = world.canvas.getContext( '2d' ); finally, Code: // world.ground.js world.ground = { } ; world.ground.level = []; world.ground.make = function( GArray, length ){ world.ctx.strokeStyle = '#000000'; world.ground.level = []; world.ctx.fillStyle = '#FFF'; world.ctx.fillRect( 0, 0, world.w, world.h ); world.ground.level = GArray; for ( world.ground.make.i = 0; world.ground.make.i <= length; world.ground.make.i ++ ){ if ( GArray[world.ground.make.i + 1] === undefined ){ GArray[world.ground.make.i + 1] = GArray[world.ground.make.i]; } world.ctx.moveTo( world.ground.make.i, ( world.h ) ); world.ctx.lineTo( world.ground.make.i, ( world.h - GArray[world.ground.make.i] ) ); } world.ctx.stroke(); world.ctx.beginPath(); } ; world.ground.create = function( func, width ){ func = ec( func ); if( func === false ){ alert( 'Pass equation as a string without the "y=", "f(x)=", "g(x)=" or similar.' ); return world; } if( func == 'perspicaciousness' ){ return world; } var temp = []; for( var x = 0; x <= width; x ++ ){ temp[x] = eval( func ); } world.ground.make( temp, width ); } ; world.ground.create.test='4'; world.ground.create( world.ground.create.test, 500 ); in the end of world.bolt.cpath,there should be a way to use the local varis X and Y, and world.ground.js's world.ground.level[] to detect it. sorry for the gigantic length. thanks in advanced. the jsnerd Greetings. I am using an image galery script written by another person - frogjs (http://www.puidokas.com/portfolio/frogjs/) This script is showing current pic in the middle of the screen and next/previous little tumbnails on right/left sides of the current. When you click the next pic, current pic is zoomed out to the left and next pic is zoomed in to the middle, then replaced by a full-size pic. Then a new tumbnail appears on the place of the next pic you clicked. Zooming and stuff is done with another thirdparty script "effects" (script.aculo.us effects.js v1.7.0) My problem is, the actual next tumbnail is not being shown until the big image is preloaded for this thumbnail. This is done to make it look smooth. So, when i click "next" picture, the next picture is shown, but switching to the following one is delayed until that following one is actually loaded. It is done by making an imgpreloader=Image() object and setting imgpreloader.onload to a function, then setting imgpreloader.src to the big image path. The big image then is supposed to be automatically loaded by browser. When its done, an onload event should fire and that should execute the function that shows the thumbnail for the big picure. Problem is, sometimes the onload event won't happen! And since it wont happen, my gallery will "stall" - it will never show next thumbnail and never allow to continue viewing. And if i show next thumbnail immediately, the next picture would be shown partially and that does not look good. Moreover, i've seen numerous image galeries on numerous sites and all of them seem to work with onload because i only see the image when its loaded, until that i see some "wait" or "grey screen" thing. Never had a problem with those stalling. Problem happens mostly with Opera and Chrome and happens seldom with IE. So, question is, do you probably know what can prevent browsers from firing and OnLoad event or from loading a picture when its suppied as an src for an Image() object? Do you know a workaround that can "poke" the browser to remind it to get the damn picture again and not to stall. |