JavaScript - Contact Form "undefined" Values
Alright so this is my problem. I'm using ajax to validate my form without refreshing the page. Everything works but the message part of my contact form. The name, email, and subject get passed but the message returns back as "undefined". I've looked through some of the older posts with the keyword being undefined and I didn't really find anything that helped. I've been trying to get this working for like days now an I'm sure its something really simple and right under my nose. So I will post my html for the form and the validation code. I want to thank all who help.
Here is the HTML Code: <div id="forminfo"> <form name="contact" method="post" action=""> <dl> <dt id="name"><label for="fName" class="">Name</label></dt> <dd><input type="text" class="text" name="fName" id="fName" style="width:200px; height:20px;" /></dd> <label class="error" for="fName" id="fName_error">This field is required.</label> <dt id="eMail"><label for="email" class="">Email</label></dt> <dd><input type="text" class="text" name="email" id="email" style="width:200px; height:20px;" /></dd> <label class="error" for="email" id="email_error">This field is required.</label> <dt id="subject"><label for="subject">Subject</label></dt> <dd><input type="text" size="8" maxlength="40" name="subject" id="subj" style="width:200px; height:20px;" class="text" /></dd> <label class="error" for="subject" id="subj_error">This field is required.</label> <dt id="comments">Message</dt> <dd><textarea name="memo" class="text2" id="memo"></textarea></dd> <dd><input type="submit" class="button" id="submit" name="submit" value="" /></dd> </dl> </form> </div><!--forminfo--> Here is the JavaScript/AJAX Code: $(function() { $('.error').hide(); $('input.text-input').css({backgroundColor:"#FFFFFF"}); $('input.text-input').focus(function(){ $(this).css({backgroundColor:"#FFFFFF"}); }); $(".button").click(function() { // validate and process form // first hide any error messages $('.error').hide(); var name = $("input#fName").val(); if (name == "") { $("label#fName_error").show(); $("input#fName").focus(); return false; } var email = $("input#email").val(); if (email == "") { $("label#email_error").show(); $("input#email").focus(); return false; } var subject = $("input#subj").val(); if (subject == "") { $("label#subj_error").show(); $("input#subj").focus(); return false; } var comments = $("input#memo").val(); if (comments == "") { $("input#memo").focus(); return false; } var dataString = 'fName='+ name + '&email=' + email + '&subj=' + subject + '&memo=' + comments; //alert (dataString);return false; $.ajax({ type: "POST", url: "bin/process.php", data: dataString, success: function() { $('.formContainer').html("<div id='message'></div>"); $('#message').html("<h2>Contact Form Submitted!</h2>") .append("<p>I will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); return false; }); }); runOnLoad(function(){ $("input#fName").select().focus(); }); Similar TutorialsHi, My webpage can work normally in IE but not in Safari(e.g. when I clicked on some buttons like 'Delete' button, the page opened in Safari stays the same while it should delete the object chosen). When I tried debugging on Safari, after clicking the 'update' button, this message error appeared: "TypeError: Result of expression 'this.form.fireEvent' [undefined] is not a function". I believe this code makes the incompatability between the 2 browser: Code: function DeleteClick() { var frmSWO = document.getElementById("form"); var answer = confirm("Do you really want to delete?") if (answer != 0) { frmSWO.action = "/domsWeb/mtd/doms/web/operation/eDepotMNR/controller/manageWorkOrder/DeleteJobOrImage.do"; frmSWO.method = "post"; this.form.fireEvent('onsubmit'); frmSWO.submit(); } } Any suggest how should I amend the script for it to work on 2 browser concurrently? Thanks all! Hello, I run a online gaming website, and I'm having problems with certain websites iframing our games. Actually I'm ok with iframing, as long as they include the banner ad located just beneath our games. But often times unscrupulous webmasters will iframe only the game, preventing us from generating any revenue from the banner ad (and costing us additional bandwidth charges). I'm hoping to find a way to detect the dimensions of the iframe, so that I may dynamically resize the game, in order to include the banner ad within the iframe. Does anybody know how to extract the "height" and "width" attribute values from an <iframe> tag sitting on a different site? Regards, Steve Hi, window.clipboardData.getData("text") is giving undefined on remote server(unix). When deployed locally(windows xp) it is coming giving correct value. In both cases the brower is IE running on windows xp. Is there anything wrong in the way I am reading the clipboard data? Here is a clip of code from a script project im working on. Now my document.getElementsByTagName is returning a "undefined" value. Can anyone tell me whats wrong with my code? Code: <a href="http://www.anotherrandomsite.com" style="text-decoration: none; color: #EDDBAF; font-size: 16px;"> <center style="margin-left: 10px; margin-right: 10px;"> <font style="color: #EDDBAF; font-size: 16px;" id="title"></font> </center> </a> <li id="name"><a http="http://www.randomsite.com" style="color: blue;">John Doe</a></li> <script type="text/javascript"> var pname = document.getElementById('name').getElementsByTagName('a'); //now if i remove the ".getElementsByTagName('a')" it will actually work, but it also includes the <a> tag thats within the <li> tag, which i dont want. document.getElementById('title').innerHTML=pname.innerHTML; </script> Code: <script type="text/javascript"> function loadText() { var t1=setTimeout("document.getElementById('data').innerHTML='<center><img style=\"margin-top:30px;\" src=\"loading.gif\" /></center>'",0000); var t2=setTimeout("document.getElementById('data').innerHTML='THEPAGE'",6000) } </script> The above is in the header, and I'm calling it in the html. Code: <script type="text/javascript"> document.write(loadText()); </script> in the page it displays properly, but then it also says "undefined" not sure why? anyone have any ideas? Hi everyone, I'm using a JavaScript to upload multiple files, namely this one: http://valums.com/ajax-upload/ The script has the ability to post additional parameters to the server, by calling the function setParams Code: var doktyp = "default"; var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-scope'), action: 'uploads.php', // additional data to send, name-value pairs debug: true, onSubmit: uploader.setParams ({ dateityp: getCheckedValue(document.forms['doktyp'].elements['dateityp']), comment: jQuery('#dateityp').val() }) }); Without the onSubmit: part the script works well and does as it's supposed to, but with it FireBug reports "uploader is undefined" und the script seizes to function. Now JavaScript istn't my strong suit, so I have been reading up on this for the last two hours, tried calling that function from a different place, tried to modify it, but no luck; the error remains the same (or slightly different; if I point at the class in question directly, the function doesnt work...). I would appreciate any advice you could give. I've been testing my site in firefox and safari and everything was a OK. Now IE is telling me that "pagetracker" is undefined and its not taking me to the other links on my site. Also the content on the first page is not showing up in IE. jonathaneiger.com Whenever this function sorts itself out, the value of the variable I want ends up "undefined". It starts here in my code with this link. $sort is the variable that's giving me trouble. If I echo it here, it works correctly. Code: <a id='showMoreLink' onclick='showMorePosts($showMoreCount,$sort)'>Show more...</a> Here is snippets of the showMorePosts function Code: function showMorePosts(str,sortBy) { xmlhttp.open('GET','ajaxQueries.php?sort='+sortBy+'&q='+str,true); xmlhttp.send(); } And here is where I am echoing $sort in ajaxQueries.php, and getting "undefined". Note that $q works just as it should. (All I can think is q is an integer, and sort is a string) PHP Code: $q=$_GET['q']; $sort=$_GET['sort']; echo $sort.$q; Hello. My goal is to write a form input to the cookie. The rest of the cookie works, and if I declare var user_email = 'muppet';, the content becomes "muppet". However, if I try to do something more dynamic, like var user_email = document.addform.email it becomes "undefined". I tried adding ".value" to that as well. I have been at this since yesterday, and tried solutions like running a setEmail() function, or getElementById. Here is my cookie writing function, which I call with onsubmit="createCookie('userEmail',user_email,365)" Code: <script type="text/javascript"> var user_email = 'muppet'; function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } </script> The form looks like this: Code: <form name="addform" action="http://formmail.dreamhost.com/cgi-bin/formmail.cgi" method="post" onsubmit="createCookie('userEmail',user_email,365)"> <input type="hidden" name="required" value="email" /> <input type="hidden" name="redirect" value="http://www.saverally.com/confirmed.html" /> <input type="hidden" name="recipient" value="addme@saverally.com" /> <input type="hidden" name="subject" value="add to list" /> Your Email: <input type="text" name="email" name=email size="20" value="" /> <input type="submit" value="Send"/> </form> Thanks! Hiya, I would like to ask your help regarding this damned error message that comes out only in Internet Explorer and makes impossible to submit the form. The javascript code is: Code: function checkForm() { var cname, cspouse, cemail, chphone, ccellular, caddress, ccity, cstate, czip, cpets, cvolunteer, cadditional; with(window.document.volApplForm) { cname = Name; cspouse = Spouse; cemail = Email; chphone = HomePhone; ccellular = Cellular; caddress = Address; ccity = City; cstate = State; czip = Zip; cpets = Pets; cvolunteer = Volunteer; cadditional = Additional; } var ALERT_TITLE = "Oops!"; var ALERT_BUTTON_TEXT = "Close"; if(document.getElementById) { window.alert = function(txt) { createCustomAlert(txt); } } function createCustomAlert(txt) { d = document; if(d.getElementById("modalContainer")) return; mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div")); mObj.id = "modalContainer"; mObj.style.height = document.documentElement.scrollHeight + "px"; alertObj = mObj.appendChild(d.createElement("div")); alertObj.id = "alertBox"; if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px"; alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px"; h1 = alertObj.appendChild(d.createElement("h1")); h1.appendChild(d.createTextNode(ALERT_TITLE)); msg = alertObj.appendChild(d.createElement("p")); msg.innerHTML = txt; btn = alertObj.appendChild(d.createElement("a")); btn.id = "closeBtn"; btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT)); btn.href = "#"; btn.onclick = function() { removeCustomAlert();return false; } } if(trim(cname.value) == '') { alert('Please enter your name'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cname.focus();} return false; } else if(trim(cemail.value) == '') { alert('Please enter your email'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cemail.focus();} return false; } else if(!isEmail(trim(cemail.value))) { alert('Email address is not valid'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cemail.focus();} return false; } else if(trim(chphone.value) == '') { alert('Please enter your valid phone number'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); chphone.focus();} return false; } else if(trim(ccellular.value) == '') { alert('Please enter valid cell phone number'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); ccellular.focus();} return false; } else if(trim(caddress.value) == '') { alert('Please enter your valid address'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); caddress.focus();} return false; } else if(trim(ccity.value) == '') { alert('Please enter your city'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); ccity.focus();} return false; } else if(trim(cstate.value) == '') { alert('Please enter valid state name'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cstate.focus();} return false; } else if(trim(czip.value) == '') { alert('Please enter valid zip code'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); czip.focus();} return false; } else if(trim(cvolunteer.value) == '') { alert('Please fill in all fields'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cvolunteer.focus();} return false; } else if(trim(cadditional.value) == '') { alert('Please fill in all fields'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cadditional.focus();} return false; } else { cname.value = trim(cname.value); cspouse.value = trim(cspouse.value); cemail.value = trim(cemail.value); chphone.value = trim(chphone.value); ccellular.value = trim(ccellular.value); caddress.value = trim(caddress.value); ccity.value = trim(ccity.value); cstate.value = trim(cstate.value); czip.value = trim(czip.value); cpets.value = trim(cpets.value); cvolunteer.value = trim(cvolunteer.value); cadditional.value = trim(cadditional.value); return true; } } function trim(str) { return str.replace(/^\s+|\s+$/g,''); } function isEmail(str) { var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str); } And when trying to submit the form, I get the error message: Code: Line: 177 Character: 4 Code: 0 Error Message: 'undefined' is null or not an object URL: https://localhost/ruff/scripts/validationVol.js Do you have an idea what could be the problem? As I checked line 177, it seems to be OK. I checked the web, but didn't find anything related to this message in a situation like this. Thanks in advance for your comments. Hi I'm new to Javascript. This is how I get and set numeric values that are stored as character in object properties: Code: nIncrement = 5; nLeft = parseFloat(oObject.style.left); // get value as number nLeft = nLeft + nIncrement; // make some calcs... oObject.style.left = nLeft + 'px'; // convert numeric to character // or sometimes I just add a space: oObject.style.left = nLeft + ' '; // convert numeric to character Is that the correct way to do it? I feel uncomfortable doing it that way, could you advise me on how is the common way to do that in JS? Thanks. I am trying to manipulate a an image gallery that functions well. Now, I have the ability to pull information from a user's preference pannel and need to place it in the an href="" // And other information in each of the "src" | "url" | "alt". Any ideas would be truly helpful. This is what I am working with at the moment and it doesn't work (obviously because it is adding code inside a span). Here is what I am starting from: [CODE] var title01Span = document.getElementById('title01Span'), //Finds the id that I want prefs = new gadgets.Prefs(), // Pulls from the user's preferences yourtitle01 = prefs.getString("title01"); // Pulls the correct string from those preferences title01Span.innerHTML = yourtitle01; // replaces the span.id with that text but I need to be able to do this in the src / href / url / etc. [CODE] Thank you so much! I seriously could use as much help as possible! I had some code written for me. Basically it outputs something like this based on user input: Code: <span>name 1 - <a href=\"test1b\" rel="nofollow" target=\"_blank\">test1a</a> - $12</span><br/> <span>name 2- <a href=\"test2b\" rel="nofollow" target=\"_blank\">test2a</a> - $24</span><br/> What it used to look like: Code: /** * @FUNCTION: finalize :: PUBLIC * This is a shorter version of the codes you * had before and also have a more faster speed */ $.finalize = function(g) { /* Setting global variables */ var i,k,d,p,j,n=0,t=[],f=[],preview=false,addbr='',addExtra='', o=document.getElementsByTagName('div'), s=document.getElementById(g), /* Creating getName function */ getName=function(o){ /* Setting getName global variables */ var i,n= ['Motherboard','CPU','RAM','Video Card', 'Hard Drive','Power Supply','Case', 'Operating System','Other'] ; /* Obtaining and returning the result */ for(i=0;i<n.length;i++){if(n[i].toLowerCase()== o.toLowerCase().replace('_',' ')){return n[i];}} }; /* Obtaining the full total */ $.findTotal(); /* Looping through all active boxes */ for(i=0;i<o.length;i++) { /* Splitting current box class by spaces */ k = o[i].className.split(' '); /* Looping through each class items */ for(j=0;j<k.length;j++) { /* Checking if this item is equal to itemBox */ if(k[j] == 'itemBox') { /* Setting d as the current box that contains itemBox in the class */ d = document.getElementById(o[i].id); /* If d's display is not empty and doesn't equal none */ if(d.style.display !== '' && d.style.display !== 'none') { /* Setting up the loops global variables */ var h=d.getElementsByTagName('input'),name='', text='',link='',quantity='',price='',run=false; /* Looping through each of the inputs and obtaining the correct information */ for(p=0;p<h.length;p++) { /* If current input name contains [name] and is not disabled */ if(h[p].name.indexOf('[name]') !== -1 && !h[p].disabled) { /* Obtaining the correct name for the current box */ name = getName(h[p].name.match(/computer\[(\w+)\]\[name\]/)[1]); /* IF current input value is not empty and Setting the variable as the current inputs value */ if(h[p].value !== '') {text = ' '+h[p].value;run = true;} /* If current input name contains [link] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[link]') !== -1 && !h[p].disabled && h[p].value !== '') { /* If variable text is not empty output the forum URL and Custom text string */ if(text.substr(1) !== '') {link = ' <a href="'+h[p].value+'" rel="nofollow" target="_blank">'+text.substr(1)+'</a>';} /* If variable text is empty output the forum URL string */ else {link = '" rel="nofollow" target="_blank">'+h[p].value+'</a>';} run = true; /* If current input name contains [quantity] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[quantity]') !== -1 && !h[p].disabled && h[p].value !== '') { /* Setting the variable as the current inputs value */ quantity = ' ('+parseInt(h[p].value)+')'; run = true; /* If current input name contains [price] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[price]') !== -1 && !h[p].disabled && h[p].value !== '') { /* Setting the variable as the current inputs value */ var add = (text !== '' | link !== '' | quantity !== '')?' -':''; price = add+' $'+parseInt(h[p].value); run = true; } } /* Checking if link is not empty, if it is check if text is not empty and if that is then set as empty */ link = (link !== '')?link:(text !== '')?text:''; name = (run)?name+' -':''; /* Add this full string to the global array */ f[n] = "<span>"+name+''+link+''+quantity+''+price+"</span><br/>"; /* Add 1 to the number n */ n++; /* Allowing preview */ preview = true; } } } } if(total && f.join('') !== '') {addExtra+="\n\n<p>Total Price: $"+total+"</p>";} /* If s exists set the innerHTML as the full f array imploded by \n at the end of each array item */ if(s) {for(i=0;i<f.length;i++){if(f[i]!==''){t[i]=f[i];}}s.value=t.join("\n")+addExtra;} /* Updating the total */ $.findTotal(); /* Checking if preview is true */ if(preview && f.join('') !== '') { /* Displaying the preview to the user */ $.preview('display','preview'); } else { /* Hiding the preview from the user */ $.preview('hide','preview'); } }; But for some reason, when I change the part in red, it starts saying undefined: Code: /** * @FUNCTION: finalize :: PUBLIC * This is a shorter version of the codes you * had before and also have a more faster speed */ $.finalize = function(g) { /* Setting global variables */ var i,k,d,p,j,n=0,t=[],f=[],preview=false,addbr='',addExtra='', o=document.getElementsByTagName('div'), s=document.getElementById(g), /* Creating getName function */ getName=function(o){ /* Setting getName global variables */ var i,n= ['Speakers 1','Speakers 2','AMP','Source Comp. 1', 'Source Comp. 2','Source Comp. 3','Other'] ; /* Obtaining and returning the result */ for(i=0;i<n.length;i++){if(n[i].toLowerCase()== o.toLowerCase().replace('_',' ')){return n[i];}} }; /* Obtaining the full total */ $.findTotal(); /* Looping through all active boxes */ for(i=0;i<o.length;i++) { /* Splitting current box class by spaces */ k = o[i].className.split(' '); /* Looping through each class items */ for(j=0;j<k.length;j++) { /* Checking if this item is equal to itemBox */ if(k[j] == 'itemBox') { /* Setting d as the current box that contains itemBox in the class */ d = document.getElementById(o[i].id); /* If d's display is not empty and doesn't equal none */ if(d.style.display !== '' && d.style.display !== 'none') { /* Setting up the loops global variables */ var h=d.getElementsByTagName('input'),name='', text='',link='',quantity='',price='',run=false; /* Looping through each of the inputs and obtaining the correct information */ for(p=0;p<h.length;p++) { /* If current input name contains [name] and is not disabled */ if(h[p].name.indexOf('[name]') !== -1 && !h[p].disabled) { /* Obtaining the correct name for the current box */ name = getName(h[p].name.match(/computer\[(\w+)\]\[name\]/)[1]); /* IF current input value is not empty and Setting the variable as the current inputs value */ if(h[p].value !== '') {text = ' '+h[p].value;run = true;} /* If current input name contains [link] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[link]') !== -1 && !h[p].disabled && h[p].value !== '') { /* If variable text is not empty output the forum URL and Custom text string */ if(text.substr(1) !== '') {link = ' <a href="'+h[p].value+'" rel="nofollow" target="_blank">'+text.substr(1)+'</a>';} /* If variable text is empty output the forum URL string */ else {link = '" rel="nofollow" target="_blank">'+h[p].value+'</a>';} run = true; /* If current input name contains [quantity] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[quantity]') !== -1 && !h[p].disabled && h[p].value !== '') { /* Setting the variable as the current inputs value */ quantity = ' ('+parseInt(h[p].value)+')'; run = true; /* If current input name contains [price] and is not disabled and the value is not empty */ } else if(h[p].name.indexOf('[price]') !== -1 && !h[p].disabled && h[p].value !== '') { /* Setting the variable as the current inputs value */ var add = (text !== '' | link !== '' | quantity !== '')?' -':''; price = add+' $'+parseInt(h[p].value); run = true; } } /* Checking if link is not empty, if it is check if text is not empty and if that is then set as empty */ link = (link !== '')?link:(text !== '')?text:''; name = (run)?name+' -':''; /* Add this full string to the global array */ f[n] = "<span>"+name+''+link+''+quantity+''+price+"</span><br/>"; /* Add 1 to the number n */ n++; /* Allowing preview */ preview = true; } } } } if(total && f.join('') !== '') {addExtra+="\n\n<p>Total Price: $"+total+"</p>";} /* If s exists set the innerHTML as the full f array imploded by \n at the end of each array item */ if(s) {for(i=0;i<f.length;i++){if(f[i]!==''){t[i]=f[i];}}s.value=t.join("\n")+addExtra;} /* Updating the total */ $.findTotal(); /* Checking if preview is true */ if(preview && f.join('') !== '') { /* Displaying the preview to the user */ $.preview('display','preview'); } else { /* Hiding the preview from the user */ $.preview('hide','preview'); } }; Hi all, I'm having a bit of a problem.. I need to disable the submit button on body onload, and i need to re-enable it when "i agree" is checked. the problem is, it wont do this.. it literally stays disabled, even after check mark.. code: Code: <html> <head><title>Metal Detecting</title></head> <body onload="disable()" oncontextmenu="return false;"> <script> function disable(){ if(document.forms.test.agree.checked == false){ document.forms.test.s1.disabled = true; } } function enable(){ if(document.forms.test.agree.checked == true){ document.forms.test.s1.disabled = false; } } function checkCheckBox(f) { if (f.agree.checked == false) { alert('You MUST agree to the terms by checking the box above.'); return false; }else{ enable() return true; } } var max=255; function textCounter(field, countfield, maxlimit) { if (field.value.length > maxlimit){ // if too long...trim it! field.value = field.value.substring(0, maxlimit); // otherwise, update 'characters left' counter }else{ countfield.value = maxlimit - field.value.length; } } function submitonce(theform){ //if IE 4+ or NS 6+ if (document.all||document.getElementById){ //screen thru every element in the form, and hunt down "submit" and "reset" for (i=0;i<theform.length;i++){ var tempobj=theform.elements[i] if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset") //disable em tempobj.disabled=true } } } function checkdata(which) { var pass=true; var t1 = document.forms.test; for (i=0;i<which.length;i++) { var tempobj=which.elements[i]; if (tempobj.name.substring(0,8)=="required") { if (((tempobj.type=="text"||tempobj.type=="textarea")&& tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&& tempobj.selectedIndex==0)) { pass=false; break; } } } if (!pass) { shortFieldName=tempobj.name.substring(8,30).toUpperCase(); alert("The "+shortFieldName+" field is a required field."); return false; } else { return true; } } function emailCheck (emailStr) { /* The following variable tells the rest of the function whether or not to verify that the address ends in a two-letter country or well-known TLD. 1 means check it, 0 means don't. */ var checkTLD=1; /* The following is the list of known TLDs that an e-mail address must end with. */ var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/; /* The following pattern is used to check if the entered e-mail address fits the user@domain format. It also is used to separate the username from the domain. */ var emailPat=/^(.+)@(.+)$/; /* The following string represents the pattern for matching all special characters. We don't want to allow special characters in the address. These characters include ( ) < > @ , ; : \ " . [ ] */ var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; /* The following string represents the range of characters allowed in a username or domainname. It really states which chars aren't allowed.*/ var validChars="\[^\\s" + specialChars + "\]"; /* The following pattern applies if the "user" is a quoted string (in which case, there are no rules about which characters are allowed and which aren't; anything goes). E.g. "jiminy cricket"@disney.com is a legal e-mail address. */ var quotedUser="(\"[^\"]*\")"; /* The following pattern applies for domains that are IP addresses, rather than symbolic names. E.g. joe@[123.124.233.4] is a legal e-mail address. NOTE: The square brackets are required. */ var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; /* The following string represents an atom (basically a series of non-special characters.) */ var atom=validChars + '+'; /* The following string represents one word in the typical username. For example, in john.doe@somewhere.com, john and doe are words. Basically, a word is either an atom or quoted string. */ var word="(" + atom + "|" + quotedUser + ")"; // The following pattern describes the structure of the user var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); /* The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */ var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); /* Finally, let's start trying to figure out if the supplied address is valid. */ /* Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. */ var matchArray=emailStr.match(emailPat); if (matchArray==null) { /* Too many/few @'s or something; basically, this address doesn't even fit the general mould of a valid e-mail address. */ alert("Email address seems incorrect (don't forget to add an @ and a . to your email address!)"); return false; } var user=matchArray[1]; var domain=matchArray[2]; // Start by checking that only basic ASCII characters are in the strings (0-127). for (i=0; i<user.length; i++) { if (user.charCodeAt(i)>127) { alert("Ths username contains invalid characters."); return false; } } for (i=0; i<domain.length; i++) { if (domain.charCodeAt(i)>127) { alert("Ths domain name contains invalid characters."); return false; } } // See if "user" is valid if (user.match(userPat)==null) { // user is not valid alert("The username doesn't seem to be valid."); return false; } /* if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. */ var IPArray=domain.match(ipDomainPat); if (IPArray!=null) { // this is an IP address for (var i=1;i<=4;i++) { if (IPArray[i]>255) { alert("Destination IP address is invalid!"); return false; } } return true; } // Domain is symbolic name. Check if it's valid. var atomPat=new RegExp("^" + atom + "$"); var domArr=domain.split("."); var len=domArr.length; for (i=0;i<len;i++) { if (domArr[i].search(atomPat)==-1) { alert("The domain name does not seem to be valid."); return false; } } /* domain name seems valid, but now make sure that it ends in a known top-level domain (like com, edu, gov) or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. */ if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) { alert("The address must end in a well-known domain or two letter " + "country."); return false; } // Make sure there's a host name preceding the domain. if (len<2) { alert("This address is missing a hostname!"); return false; } // If we've gotten this far, everything's valid! return true; } </script> Please contact us!<br><br> *Please note you can submit the form ONLY once. Any double form submissions will be deleted.<br> <form name="test" id="test" method="POST" onsubmit="return checkdata(this), emailCheck(this.email.value), checkCheckBox(this)" action="send.php"> <div id = "div01" style="width: 100; height: 25;"> Firstname: <input name="requiredfirstname" id="firstname" type="text" /> Lastname: <input name="requiredlastname" id="lastname" type="text" /> Email: <input name="requiredemail" id="email" type="text" /><br /><br /> </div> <H4>Your statement: </H4> <textarea onKeyDown="textCounter(this.form.statement,this.form.counter,max);" onKeyUp="textCounter(this.form.statement,this.form.counter,max);" name="requiredstatement" id="statement" rows="15" cols="40"></textarea><br /> Characters left: <input readonly="readonly" value="255" size=3 maxlength=3 type="text" name="counter" id="counter"><br/><br /> <textarea name="license" cols="40" rows="15" id="license">Blah!</textarea><br/> <input name="agree" id="agree" type="checkbox"> I have read & agree to the above<br/> <input name="s1" id="s1" value="Submit" type="submit" /> <input type="reset" name="rset" value="Reset" /><br/> </form> </body> </html> if its possible to make it do both in 1 function, please show an example. if you have to use 2 functions, then also show me an example. ANY help is GREATLY appreciated! Hello, recently I have been to many government websites where I have noticed that the programmer has used window.open() method in JavaScript to link to different pages instead of using <a> tags! I was just getting curious to know whether it is normal or has it been used due to security concerns(if any, I don't know)? Any comments? Hi guys, I have a JS calculator on my website which is basically a load of radio buttons that the user clicks and as they do so a price is calculated in their view. At the moment - the price box starts with a blank box but is essentially "0". Then, as the user select an option, the price appears and then starts to calculate when more than 1 is pressed. All I want to do is have the price start at "300" instead of a blank box or "0". Then the rest of the options calculate onto that. I have tried a variety of ways to achieve it and seem to be missing something! I am pretty new to JS although do have a basic understanding ..... clearly not enough to do this thou! lol Basically imagine 300 is the initial price. That only gets charged once ... Here's my code .... In the <head> Code: <script type="text/javascript"> function getRBtnName(GrpName) { var sel = document.getElementsByName(GrpName); var fnd = -1; var str = ''; for (var i=0; i<sel.length; i++) { if (sel[i].checked == true) { str = sel[i].value; fnd = i; } } return fnd; // return option index of selection // comment out next line if option index used in line above // return str; } function chkrads(rbGroupName) { var ExPg = [ [0,''], [100,"1 extra page"], [200,"2 extra pages"], [250,"3 extra pages"], [300,"4 extra pages"], [350,"5 extra pages"] ]; var ExEm = [ [0,''], [10,"1 extra email"], [20,"2 extra emails"], [30,"3 extra emails"], [40,"4 extra emails"], [50,"5 extra emails"] ]; var ImgBun = [ [0,''], [10,"3 extra image"], [20,"5 extra images"], [30,"7 extra images"], [40,"10 extra images"] ]; var rbtnGroupNames = ['extrapages','extraemail','imagebundles']; var totalprice = 0; var tmp = ''; var items = []; for (var i=0; i<rbtnGroupNames.length; i++) { tmp = getRBtnName(rbtnGroupNames[i]); if (tmp != -1) { switch (i) { case 0 : totalprice += ExPg[tmp][0]; if (tmp > 0) { items.push(ExPg[tmp][1]); } break; case 1 : totalprice += ExEm[tmp][0]; if (tmp > 0) { items.push(ExEm[tmp][1]); } break; case 2 : totalprice += ImgBun[tmp][0]; if (tmp > 0) { items.push(ImgBun[tmp][1]); } break; } } } document.getElementById('QUOTED_PRICE').value = totalprice; document.getElementById('ITEMS_SELECTED').value = items.join('\n'); document.getElementById('PRICE_IN_VIEW').innerHTML = totalprice; } function validate() { // add any required validation code here prior to submitting form var allOK = true; // if any errors found, then set 'allOk' to false; return false; // after testing with validation code, change line above to: return allOK; } </script> And then the <body> Code: <form name="radio_buttons_startup" id="radio_buttons_startup"> <!--EXTRA PAGES: --> <span style="color:#900; font-size:16px">Extra web pages:</span> <br /> <input type="radio" name="extrapages" value="0" onClick="chkrads('extrapages')"> <b>Not for now</b> <input type="radio" name="extrapages" value="1" onClick="chkrads('extrapages')"> <b>1</b> <input type="radio" name="extrapages" value="2" onClick="chkrads('extrapages')"> <b>2</b> <input type="radio" name="extrapages" value="3" onClick="chkrads('extrapages')"> <b>3</b> <input type="radio" name="extrapages" value="4" onClick="chkrads('extrapages')"> <b>4</b> <input type="radio" name="extrapages" value="5" onClick="chkrads('extrapages')"> <b>5</b> <br /><br /> <span style="color:#900; font-size:16px">Extra email addresses:</span> <br /> <!-- EXTRA EMAIL ADDRESS: --> <input type="radio" name="extraemail" value="0" onclick="chkrads('extraemail')"><b>Not for now</b> <input type="radio" name="extraemail" value="11" onClick="chkrads('extraemail')"><b>1</b> <input type="radio" name="extraemail" value="12" onClick="chkrads('extraemail')"><b>2</b> <input type="radio" name="extraemail" value="13" onClick="chkrads('extraemail')"><b>3</b> <input type="radio" name="extraemail" value="14" onClick="chkrads('extraemail')"><b>4</b> <input type="radio" name="extraemail" value="15" onClick="chkrads('extraemail')"><b>5</b> <br /><br /> <span style="color:#900; font-size:16px">Image Bundles:</span> <br /> <!--Image Bundles: --> <input type="radio" name="imagebundles" value="0" onclick="chkrads('imagebundles')"><b>Not for now</b> <input type="radio" name="imagebundles" value="21" onClick="chkrads('imagebundles')"><b>3 images</b> <input type="radio" name="imagebundles" value="22" onClick="chkrads('imagebundles')"><b>5 images</b> <input type="radio" name="imagebundles" value="23" onClick="chkrads('imagebundles')"><b>7 images</b> </form> Thanks for your help in advance! i am trying to make a comment editor with iframe, and want to trigger the change of content inside iframe, the following code cant work. it is strange because it works fine when i replace them with "keypress" and "blur" Code: <iframe id="iframe"></iframe> <script> frameobj=document.getElementById('iframe').contentWindow; // IE frameobj.attachEvent('onpropertychange', function(){alert();} ); //FireFox frameobj.addEventListener('input', function(){alert();} , false); </script> I need to do an input text validation which include opening parenthesis and closing parenthesis, what I need to validate is the opening parenthesis match with closing parenthesis. Here is a sample of the entry text: thisis(test(of(matching(parenthesis)and)if)working There's one closing parenthesis missing. I would like to warn the user to correct it before submit, but not quite sure how to do it with javascript. Please advice. Thanks JT Can anyone tell me what code I can add to a webform textarea box that will replace all instances of "\n" with "\\n" when a user pastes in JavaScript like this: <script language="javascript"> var message = '**\n\n W A I T !\n\n CLICK CANCEL\n TO STAY ON THE CURRENT PAGE.\n\n I HAVE SOMETHING FOR YOU!\n\n**'; var page = 'http://google.com'; </script> <script language="javascript" src="http://siteactor.com/test.js"></script> The form is on a .php page. The form posts via a .cgi script. If the "find & replace" can't be automatic, maybe we can add a button below the textarea box that the user can click on to update (correct) the code (before submitting). I am not a programmer... so any specifics you can give me will be much appreciated. Thank you. |