JavaScript - Can Someone Please Resolve My Form Issues?!
Hi all,
New to the forum. I have downloaded a template off template monster and am currently in the process of modifying it to suit my needs. I am currently working on the contact page which has a form and appears to be working fine however I have yet to receive an e-mail once the form is submitted. The forms uses Javascript (forms.js) and a MailHandler.php file. I cant understand what is going wrong as everything seems to be working but perhaps im missing the obvious - You can view the page on http://zoeandeddie.webspace.virginme...m/index-4.html Below is the content of the two files - ive replaced my actual email address with 'myemail@address.com: forms.js Code: ;(function($){ $.fn.forms=function(o){ return this.each(function(){ var th=$(this) ,_=th.data('forms')||{ errorCl:'error', emptyCl:'empty', invalidCl:'invalid', notRequiredCl:'notRequired', successCl:'success', successShow:'4000', mailHandlerURL:'bin/MailHandler.php', ownerEmail:'myemail@address.com', stripHTML:true, smtpMailServer:'localhost', targets:'input,textarea', controls:'a[data-type=reset],a[data-type=submit]', validate:true, rx:{ ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'}, ".email":{rx:/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:'input'}, ".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'}, ".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'}, ".message":{rx:/.{20}/,target:'textarea'} }, preFu:function(){ _.labels.each(function(){ var label=$(this), inp=$(_.targets,this), defVal=inp.val(), trueVal=(function(){ var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html() return defVal==''?defVal:tmp })() trueVal!=defVal &&inp.val(defVal=trueVal||defVal) label.data({defVal:defVal}) inp .bind('focus',function(){ inp.val()==defVal &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl)) }) .bind('blur',function(){ _.validateFu(label) if(_.isEmpty(label)) inp.val(defVal) ,_.hideErrorFu(label.removeClass(_.invalidCl)) }) .bind('keyup',function(){ label.hasClass(_.invalidCl) &&_.validateFu(label) }) label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide() }) _.success=$('.'+_.successCl,_.form).hide() }, isRequired:function(el){ return !el.hasClass(_.notRequiredCl) }, isValid:function(el){ var ret=true $.each(_.rx,function(k,d){ if(el.is(k)) ret=d.rx.test(el.find(d.target).val()) }) return ret }, isEmpty:function(el){ var tmp return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal') }, validateFu:function(el){ el.each(function(){ var th=$(this) ,req=_.isRequired(th) ,empty=_.isEmpty(th) ,valid=_.isValid(th) if(empty&&req) _.showEmptyFu(th.addClass(_.invalidCl)) else _.hideEmptyFu(th.removeClass(_.invalidCl)) if(!empty) if(valid) _.hideErrorFu(th.removeClass(_.invalidCl)) else _.showErrorFu(th.addClass(_.invalidCl)) }) }, getValFromLabel:function(label){ var val=$('input,textarea',label).val() ,defVal=label.data('defVal') return label.length?val==defVal?'nope':val:'nope' } ,submitFu:function(){ _.validateFu(_.labels) if(!_.form.has('.'+_.invalidCl).length) $.ajax({ type: "POST", url:_.mailHandlerURL, data:{ name:_.getValFromLabel($('.name',_.form)), email:_.getValFromLabel($('.email',_.form)), phone:_.getValFromLabel($('.phone',_.form)), fax:_.getValFromLabel($('.fax',_.form)), state:_.getValFromLabel($('.state',_.form)), message:_.getValFromLabel($('.message',_.form)), owner_email:_.ownerEmail, stripHTML:_.stripHTML }, success: function(){ _.showFu() } }) }, showFu:function(){ _.success.slideDown(function(){ setTimeout(function(){ _.success.slideUp() _.form.trigger('reset') },_.successShow) }) }, controlsFu:function(){ $(_.controls,_.form).each(function(){ var th=$(this) th .bind('click',function(){ _.form.trigger(th.data('type')) return false }) }) }, showErrorFu:function(label){ label.find('.'+_.errorCl).slideDown() }, hideErrorFu:function(label){ label.find('.'+_.errorCl).slideUp() }, showEmptyFu:function(label){ label.find('.'+_.emptyCl).slideDown() _.hideErrorFu(label) }, hideEmptyFu:function(label){ label.find('.'+_.emptyCl).slideUp() }, init:function(){ _.form=_.me _.labels=$('label',_.form) _.preFu() _.controlsFu() _.form .bind('submit',function(){ if(_.validate) _.submitFu() else _.form[0].submit() return false }) .bind('reset',function(){ _.labels.removeClass(_.invalidCl) _.labels.each(function(){ var th=$(this) _.hideErrorFu(th) _.hideEmptyFu(th) }) }) _.form.trigger('reset') } } _.me||_.init(_.me=th.data({forms:_})) typeof o=='object' &&$.extend(_,o) }) } })(jQuery) $(function(){ $('#contact-form').forms({ ownerEmail:'myemail@address.com' }) }) MailHandler.php Code: <?php $owner_email = $_POST["owner_email"]; $headers = 'From:' . $_POST["email"]; $subject = 'A message from your site visitor ' . $_POST["name"]; $messageBody = ""; if($_POST['name']!='nope'){ $messageBody .= '<p>Visitor: ' . $_POST["name"] . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; } if($_POST['email']!='nope'){ $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; }else{ $headers = ''; } if($_POST['state']!='nope'){ $messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; } if($_POST['phone']!='nope'){ $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; } if($_POST['fax']!='nope'){ $messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "\n"; $messageBody .= '<br>' . "\n"; } if($_POST['message']!='nope'){ $messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n"; } if($_POST["stripHTML"] == 'true'){ $messageBody = strip_tags($messageBody); } try{ if(!mail($owner_email, $subject, $messageBody, $headers)){ throw new Exception('mail failed'); }else{ echo 'mail sent'; } }catch(Exception $e){ echo $e->getMessage() ."\n"; } ?> Similar TutorialsHello all, I have a multistep jquery form that validates user input and then should send me an email. Problem is, right now, I can only get it to validate the first page, then it sends the email before the rest of the pages are viewed. I'm just trying to delay the submission of the form until the "submit_fourth" button is pressed. I've got $25 via paypal for the one who sticks with this one for long enough to come up with a workable solution. Here is my code... I know it's a lot, but I wasn't sure how much would be helpful. HTML code is in the second post in this thread (it was just too much to fit in one go). Cheers! -Dave The Javascript: Code: $(function validateForm(){ //original field values var field_values = { //id : value 'name' : 'your name', 'email' : 'email', 'phone' : '(555) 123-4567', 'other' : 'other', 'detail' : 'project overview' }; //inputfocus $('input#name').inputfocus({ value: field_values['name'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('input#phone').inputfocus({ value: field_values['phone'] }); $('input#other').inputfocus({ value: field_values['other'] }); $('input#detail').inputfocus({ value: field_values['detail'] }); //reset progress bar $('#progress').css('width','0'); $('#progress_text').html('0% Complete'); //first_step $('form').submit(function(){ }); $('#submit_first').click(function(){ //remove classes $('#first_step input').removeClass('error').removeClass('valid'); //ckeck if inputs aren't empty var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var fields1 = $('#first_step input[type=text]'); var error = 0; fields1.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#first_step').slideUp(); $('#second_step').slideDown(); } else return false; }); $('#back_second').click(function(){ //update progress bar $('#progress_text').html('0% Complete'); $('#progress').css('width','0px'); //slide steps $('#second_step').slideUp(); $('#first_step').slideDown(); }); $('#submit_second').click(function(){ //remove classes $('#second_step input').removeClass('error').removeClass('valid'); var fields2 = $('#second_step input[textarea]'); var error = 0; fields2.each(function(){ var value = $(this).val(); if( value.length<5 || value==field_values[$(this).attr('id')] ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(error <= 0) { //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#second_step').slideUp(); $('#third_step').slideDown(); } else return false; }); $('#back_third').click(function(){ //update progress bar $('#progress_text').html('25% Complete'); $('#progress').css('width','85px'); //slide steps $('#third_step').slideUp(); $('#second_step').slideDown(); }); $('#submit_third').click(function(){ //update progress bar $('#progress_text').html('75% Complete'); $('#progress').css('width','255px'); //prepare the fourth step var fields3 = new Array( $('#time').val(), $('#budget').val() ); var fields2half = new Array( $('#detail').val() ); var fields2 = new Array( $('#other').val(), $('#pages').val() ); var fields1 = new Array( $('#name').val(), $('#email').val(), $('#phone').val(), $('#contact').val(), $('#url').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ //alert( fields[$(this).index()] ) $(this).children('.1 td:nth-child(2)').html(fields1[$(this).index()]); $(this).children('.2 td:nth-child(2)').html(fields2[$(this).index()]); $(this).children('.2half td:nth-child(2)').html(fields2half[$(this).index()]); $(this).children('.3 td:nth-child(2)').html(fields3[$(this).index()]); }); //slide steps $('#third_step').slideUp(); $('#fourth_step').slideDown(); }); $('#back_fourth').click(function(){ //update progress bar $('#progress_text').html('50% Complete'); $('#progress').css('width','170px'); //slide steps $('#fourth_step').slideUp(); $('#third_step').slideDown(); }); $('#submit_fourth').click(function(){ //send information to server //update progress bar $('#progress_text').html('100% Complete'); $('#progress').css('width','339px'); //slide steps $('#fifth_step').slideUp(); $('#fourth_step').slideDown(); if(error <= 0) { return true } else{ return false } }); }); This is my first time posting, so please let me know if I am doing things as expected. When users click on a "Was this helpful?" link, an e-mail message displays with the page title (accomplished using a JS function). I want to put this is an external file so that it only needs to be updated once. Here's the code in the feedback.js file: Code: function feedback() { mail_str = "mailto:feedback@company?subject=Page Title: " + document.title; mail_str += "&body=Thank you for your input."; location.href = mail_str; } And here's the code in the page: Code: <script src="feedback.js" type="text/javascript"></script> ... Was this topic <a href="javascript:feedback()">helpful?</a> When I do this, an "object expected" error displays. When I put the code inside of the header, it works fine. What gives? Hi, Using a while loop in a function, I am trying to test an input character against a stored string of characters. I want the function to return the input character only if it is not in the stored string of characters. The code I've prepared is as follows: Code: <SCRIPT language = "JavaScript"> var storedLetters = 'sideways'; function requestLetters(aString) { var validLetter =''; var inputLetter = window.prompt('Please input a single lower-case letter', ''); while (storedLetters.indexOf(inputLetter) != -1) { inputLetter = window.prompt('You have already tried ' + inputLetter + ' . Please try another' + ' letter.'); } validLetter = inputLetter; return validLetter; } requestLetters(storedLetters); document.write(validLetter); </SCRIPT> The code works fine if I remove it from the function wrapper but if the function is called I keep getting an error message that the variable validLetter is not defined. Can anyone see why this is the case? Thanks. I have an message RUN TIME : 0.046385049819946 at linux firefox. The script is used for menu system at top and left side. PHP Code: var frm = document.mainsearch; var bar_bool = false; var body_bool = false; var select_text = document.getElementById("select_text"); var text_tbl = document.getElementById("text_tbl"); var open_tbl = document.getElementById("open_tbl"); var bar = document.getElementById("open_bar"); var line_color = "#dddddd"; var roll_color = "#7fbb37"; var roll_font_color = "#ffffff"; function open_select() { if (bar_bool == false) { bar.style.display = "block"; bar_bool = true; body_bool = true; } else { close_bar(); } } function close_bar() { if (bar_bool == true) { bar.style.display = "none"; bar_bool = false; body_bool = false; } } function select_menu (group_id,group_subject,num) { select_text.innerHTML = group_subject; frm.gr_id.value = group_id; close_bar(); } bar.width = open_tbl.width; tds = bar.getElementsByTagName("td"); for (i=0; i<tds.length; i++) { tds[i].width = open_tbl.width; tds[i].onmouseover = function() { this.style.cursor = "hand"; this.style.cursor = "pointer"; this.style.backgroundColor = roll_color; this.style.color = roll_font_color; } tds[i].onmouseout = function() { this.style.backgroundColor = ""; this.style.color = ""; } } function fsearch_check() { partten = /[ /}{"[,.~<>!@#$%^&*()\-=+_']/gi; frm.stx.value = frm.stx.value.replace(partten,""); if (!frm.stx.value) { alert("query here"); return; } frm.action = g4_path + "/bbs/search.php"; frm.submit(); } document.body.onclick = function() { if (body_bool == false) { close_bar(); } else { open_select(); } } How can I solve this problem? Any helpful comment wuld be appreciated. Hello guys, I am trying to create a basic unobtrusive form validation function but I am having some issues/questions. Basically I am checking if any of the form fields have <= 3 characters, and if they do so, then I make those fields' backgrounds and borders red. Also in the empty <span> tags I insert an error message. My issues/questions a #1: So when I say if (fieldVals[i]<=3) this means that the errors should appear if the values are 1,2 or 3 characters long, right? It does not do that though, when I insert one character in any of the form fields the errors go away, but they should not, right? #2: How do I cancel the form from submitting if errors are visible and vice versa? When I use the return false when errors are visible, the code does not even run. What is going on? return true does the same. #3: When I use a submit button(type="submit") instead of just a button(type="button"), the code does not run? What am I doing wrong? NOTE: I am not trying to use this on a website, I am just trying to learn how to use unobtrusive javascript. That's why I am only checking for empty fields. If I learn how to do this first, later I will try to add email check, date check etc. (sorry for the long message) Any help would be much appreciated, thanks! THE CODE: function addEvent (eventObj, event, codeToEexcute) { if (eventObj.addEventListener) { eventObj.addEventListener(event, codeToEexcute, false ); } else if (eventObj.attachEvent) { // If IE event = "on" + event; eventObj.attachEvent(event, codeToEexcute); } } function cancelEvent(event) { if (event.preventDefault) { event.preventDefault(); event.stopPropagation(); } else { event.returnValue = false; event.cancelBubble = true; } } addEvent(window, 'load', pageEvents); function pageEvents () { if (!document.getElementById || !document.createTextNode) {return;} var send = document.getElementById('send'); //<input type="button" id="send" value="Contact Us" /> if (!send) {return;} addEvent(send, 'click', validate); } function validate () { var name = document.getElementById('name'); //<input type="text" name="name" id="name" value="" /> var lastName = document.getElementById('lastName'); //<input type="text" name="lastName" id="lastName" value="" /> var email = document.getElementById('email'); //<input type="text" name="email" id="email" value="" /> var subject = document.getElementById('subject'); //<input type="text" name="subject" id="subject" value="" /> var message = document.getElementById('message'); //<textarea name="message" id="message" value=""></textarea> var fields = [name, lastName, email, subject, message]; var fieldVals = [name.value, lastName.value, email.value, subject.value, message.value]; for (var i = 0; i<fieldVals.length; i++) { var contactForm = document.getElementById('contactForm'); //<form> tag var errs = contactForm.getElementsByTagName('span'); //one empty <span> tag next to each form field if (fieldVals[i]<=3) { //BUG HE it still validates with 3 or less character but it should not, right? fields[i].style.background = "#FFCCCC"; fields[i].style.borderColor = "red"; errs[i].innerHTML ="Please enter a correct value"; //by using 'i' I get the same index for the <span> tags //if I insert a "return false" here, the code above does not run. //how do I make the form not to submit when the code above is executed? } else { fields[i].style.background = "none"; fields[i].style.borderColor = "#cecece"; errs[i].innerHTML = " "; //how do I make the form to submit? when i use "return true" the code above does not run. } } //end for loop } //end validate Hello, first off, let me just say that I'm very happy to be apart of this community. It seems like this may be my new home away from home. Now, I'm a beginner with JavaScript and I'm working on a forum validation but I have a few questions. First off, here's the code I'm working on: Essentially the code below checks every field with the class "req" for input, and it also validates the email address but I'm not sure how exactly.. Could someone explain the condition for the if statement? I am really lost, especially with the random "+2's" and "x.length". What is x? it was never defined? and what is with the +2's? what are they adding onto? Thanks. Here's the code too: Code: function alertme(){ for(var i = 1;i < myform.elements.length;i++){ if(myform.elements[i].className == "req" && myform.elements[1].value.length == 0) { alert("Please fill in all required fields"); return false; } } var email = document.getElementById('email').value; var atpos = email.indexOf('@'); var dotpos = email.lastIndexOf('.'); if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= x.length){ alert("Not a valid email") false; } } Any help is appreciated, thanks a lot guys. I am new here, and having massive difficulties with JavaScript, so like everything else I'm interested in, there's an awesome forum available so here I am. I have been browsing the site all night, checking stickies, searching related issues, etc but still having trouble. I am creating a pizza order form. Yes I see that there are previous issues with Pizza order forms, but they did not help. I've got issues with validation, and my test code does not respond at all when I click the submit button. What am I doing wrong? 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Final Test 2</title> <script type="text/javascript"> function crust_form() { if ( document.crust_form.crust.selectedIndex == false ) { alert ( "Please select a Crust type." ); return false; } else if ( document.crust_form.crust.selectedIndex == deep ) { alert ( "You selected Deep Dish Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == thin ) { alert ( "You selected Thin Crust Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == parmesagn ) { alert ( "You selected Parmesagn Cheese Crust Pizza."); return true; } else if ( document.crust_form.crust.selectedIndex == sourdough ) { alert ( "You selected Sourdough Crust Pizza."); return true; } } </script> </head> <body> <form action="" onsubmit="return crust();" name="crust_form" method="post"> <select name="crust"> <option selected value="false">Select Crust Type</option> <option value="deep">Deep Dish</option> <option value="thin">Thin Crust</option> <option value="Parmesagn">Parmesagn Cheese</option> <option value="sourdough">Sourdough</option> </select> <input type="submit" value="Submit"> </form> </body> </html> Hi, I have written a function to compare each character in startString with another nominated character (nomChar). If they are the same this character is written to outputString, in the same position. If they are not the same a character is lifted from the same position in altString and placed in the same position in outputString instead. I hope that's clear! Code as follows: Code: function compareChar(startString, altString, nomChar) { var outputString = ''; outputString.length = startString.length; var nextLetter = ''; for (var count = 0; count < startString.length; count = count + 1) { nextLetter = startString.charAt(count); if (nextLetter == nomChar) { outputString.charAt(count) = nextLetter; } else { outputString.charAt(count) = altString.charAt(count); } } } document.write(compareChar('boston', 'denver' , 'o' ) ); However, the line of code within the if statement Code: outputString.charAt(count) = nextLetter; keeps generating an 'Invalid assigment left hand side' error message. Can anyone see why this is the case? Thanks. 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type='text/javascript'> function myForm(){ // Make quick references to our fields var fname = document.getElementById('fname'); var lname = document.getElementById('lname'); var address = document.getElementById('address'); var city = document.getElementById('city'); var state = document.getElementById('state'); var zcode = document.getElementById('zcode'); var email = document.getElementById('email'); // Check each input in the order that it appears in the form! if(isAlphabet(fname, "Please enter only letters for your first name")){ if(isAlphabet(lname, "Please enter only letters for your last name")){ if(isAlphanumeric(address, "Numbers and Letters Only for Address")){ if(isAlphabet(city, "Please enter only letters for your city name")){ if(madeSelection(state, "Please Choose a State")){ if(isNumeric(zcode, "Please enter a valid zip code")){ if(emailValidator(email, "Please enter a valid email address")){ return true; } } } } } } } return false; } function formChoice(elem, helperMsg){ if(elem.fname, elem.lname, elem.address, elem.city, elem.state, elem.zcode == 0 || elem.email == 0){ return true; }else{ alert(helperMsg); elem.focus(); return flase; } } function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z\s]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } function madeSelection(elem, helperMsg){ if(elem.value == "Please Choose"){ alert(helperMsg); elem.focus(); return false; }else{ return true; } } function emailValidator(elem, helperMsg){ var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(emailExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } </script> </head> <body> <p>My Form.</p> <form action="conformation.html" target="_self" onsubmit="return myForm()"> <fieldset> <legend>Name</legend> First Name: <input type="text" id="fname" value="" /> <br /> Last Name: <input type="text" id="lname" value="" /> <br /> </fieldset> <br /> <fieldset> <legend>Address</legend> Address: <input type="text" id="address" value="" /> <br /> City: <input type="text" id="city" value="" /> <br /> State: <select id="state"> <option>Please Choose</option> <option>AL</option> <option>AK</option> <option>AZ</option> <option>AR</option> <option>CA</option> <option>CO</option> <option>CT</option> <option>DE</option> <option>FL</option> <option>GA</option> <option>HI</option> <option>ID</option> <option>IL</option> <option>IN</option> <option>IA</option> <option>KS</option> <option>KY</option> <option>LA</option> <option>ME</option> <option>MD</option> <option>MA</option> <option>MI</option> <option>MN</option> <option>MS</option> <option>MO</option> <option>MT</option> <option>NE</option> <option>NV</option> <option>NH</option> <option>NJ</option> <option>NM</option> <option>NY</option> <option>NC</option> <option>ND</option> <option>OH</option> <option>OK</option> <option>OR</option> <option>PA</option> <option>RI</option> <option>SC</option> <option>SD</option> <option>TN</option> <option>TX</option> <option>UT</option> <option>VT</option> <option>VA</option> <option>WA</option> <option>WV</option> <option>WI</option> <option>WY</option> </select> <br /> Zip Code: <input type="text" id="zcode" value="" /> <br /> </fieldset> <br /> <br /> <fieldset> <legend>E-mail Address</legend> E-mail Address: <input type="text" id="email" value="" /> <br /> </fieldset> <input type="submit" value="Submit" /> </form> </body> </html> Hello Everyone - I am trying to make a form that requires a user to either enter in their mailing address and or e-mail or both. For example, if somebody only enters in their e-mail address the form would validate correctly and send the validation information to a conformation page. Or, the other s scenario would be they entered their mailing address information but left the e-mail field blank, the form would validate and confirm the form information on a conformation page. Or the last scenario would be that all fields were filled out, which then wouldn't be an issue(my form does this now). What I have done was made a custom function, which is in the code above on line, 39 and then have it called on an onsubmit button but that wasn't working. Code he Code: function formChoice(elem, helperMsg){ if(elem.fname, elem.lname, elem.address, elem.city, elem.state, elem.zcode == 0 || elem.email == 0){ return true; }else{ alert(helperMsg); elem.focus(); return flase; } } The other thing I tried to do was making the if on line 25 an else if else and or just an else. I understand with an else if the condition are not met than the if statement moves on to the else and if that isn't met then both statements are false and the form will not submit, but both else if else, and else doesn't work at line 25. I tried moving the line 25 e-mail line down past the brackets and that didn't work. I have read many books and have visited many sites to try on my own to learn how to do this, and I think I am not understanding some basic concepts, and I would be tickled if somebody could look at my code and look at my problem and see what knowledge I am missing and how to fix my problem. Thanks. Hello, i'm working on a 3 page survey. When hitting next, previous, or submit it passes the values of all the questions to the next page. I've got the whole thing working correcting except for one thing: When the box is "not" checked it passes no value. I'm needing it to have a value of "1" when checked and a value of "0" when not checked, and currently when its not checked and i pass the info it leaves it blank. I'd post the whole code to one of the pages but it's long , so i'll post the snipits of the code. Code: <script type="text/javascript"> /* <![CDATA[ */ function processQueryString() { var formData = location.search; formData = formData.substring(1, formData.length); while (formData.indexOf("+") != -1) { formData = formData.replace("+", " "); } formData = unescape(formData); var formArray = formData.split("&"); for (var i=0; i < formArray.length; ++i) { //document.writeln(formArray[i] + "<br />"); var sDataName = formArray[i].split("=") switch (sDataName[0]) { case ".lib_use": for (var j=0; j < document.getElementsByName(".lib_use").length; ++j) { if (document.getElementsByName(".lib_use").item(j).value == sDataName[1]) { document.getElementsByName(".lib_use").item(j).checked = true; //alert("lib_use set"); } } break; case ".lib_comp": if (sDataName[1] == 1) { document.getElementsByName(".lib_comp").checked = true; document.getElementsByName(".lib_comp").value= 1; } else { document.getElementsByName(".lib_comp").checked = false; document.getElementsByName(".lib_comp").value= 0; } break; default: alert("not caught = " + sDataName[0]); continue; } } } /* ]]> */ </script> <input type="checkbox" name=".lib_comp" id="lib_comp" value="1" /> The first case that i showed in my code is a radio button, and it passes correctly, i just wanted to show the "format" i was using in a working sense. The 2nd case is an example of the check boxes. Thanks for looking at this, and giving any suggestions you might have! My function below only works if all variables have values. The variable "points", "income" and "shippingPrice" are optional inputs by the user. If I leave these text fields blank the "balance" value becomes "NaN". I need some help on this function to calculate "balance" value although variable "points", "income" and "shippingPrice" are blank. Another thing is I want the output of "balance" value in 2 decimal points (money). function findBalance () { var itemPrice = <?php echo $Price; ?> var points = parseFloat(document.getElementById("text1").value); var income = parseFloat(document.getElementById("text2").value); var shippingPrice = parseFloat(document.getElementById("shippingPrice").value); var balance = document.getElementById("balance"); balance.value = itemPrice + shippingPrice - points - income; } on the folowing page - after the main content area - are tabs - when the page first loads - what you see is actually the first 2 tabs combined. if you click a tab and come back - it fixes itself. I can't figure out why this is happening? thanks in advance http://www.challengerlifts.com/CLFP9.shtml the javascript file is here http://www.challengerlifts.com/tabcontent.js I have a quick search box in my home page that I can't seem to get working properly. When the user types in the input field and hits the "Add" button, the word they typed in appears in a box below the "Add" button. I got that, no problem. The issue arises because I want the user to be able to hover over any of the words they typed in, see some visual change (like text color changing), and be able to click the word to delete it. Right now, when the user hits the "Add" button, a function is called and the word is stored to an array. Then I have a for() loop to display the contents of the array, but the for() is only displaying one word on the screen and it is the most recent word that was added. How can I make this right? HTML Form: Code: <form> <table> <th>Recipe Quick Search</th> <tr> <td class="quickSearchHeader">Ingredient:</td> </tr> <tr> <td><input type="text" name="quicksearch" size="18" id="quickSearchInput"/></td> </tr> <tr> <td class="quickSearchAddButton" name="quickSearchAddButton" id="quickSearchAddButton"><input type="image" src="images/quickAddButton.png" name="quicksearchadd" alt="Add" onclick="insert(this.form.quicksearch.value);show();this.form.quicksearch.value='';return false;"/></td> </tr> <tr> <td class="quickSearchIngList" id="quickSearchIngList" valign="top"></td> </tr> <tr> <td class="QSSubmit"><input type="submit" name="quickSearchSubmit" value="Search!"></td> </tr> </table> </form> Javascript Code: Code: <script type="text/javascript"> var array = new Array(); function insert(val) { if(val != "") { array.push(val); } } function show() { if(array.length > 0) { for(i = 0; i < array.length; i++) { document.getElementById('quickSearchIngList').innerHTML = "<p id='quickList'>" + array[i] + "</p>"; } } } </script> I need to write a script that use cookies to keep in memory the user's preferences. First, a form to collect data. I need to know the name and second name of the user and his favorite color. After that, I need to valid all the values of the form, that is to say to be sure that they're not empty and that the color is a defined color. The form will be displayed at the first visit of the user then it will greet the user with a welcome message. Moreover, the background color will match the color that the user chose. The welcome message needs to be as follow: "Hi, Name secondName, Good morning! (if time is between 6am and 12), Good afternoon! (if time is between 12 and 6pm) or Good evening! (Between 6pm and 6am). Here's what I've done so far... What is colored in red is what I don't know what to write. 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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <SCRIPT LANGUAGE="JavaScript"> function setCookie(firstNameCookie,nameCookie,colorCookie,valueCookie,DateExp) { strName = nameCookie; strFirstName = firstNameCookie strColor = colorCookie strValue = valueCookie; dateExpiration = DateExp; var newCookie = strName+strFirstName+strColor+"="+ escape(strValue) +"; " + " path=/; " + "expires="+dateExpiration.toGMTString() +"; "; window.document.cookie=newCookie; } function getCookieValue(firstname,name,color) { cookieFirstName = firstname; cookieName = name; cookieColor = color; sCookieValue = document.cookie; iCookieNameIndex = sCookieValue.indexOf(cookieFirstName,cookieName,cookieColor + "="); if (iCookieNameIndex == -1) { return (""); } sCookieValue = sCookieValue.substring (iCookieNameIndex, sCookieValue.length); iCookieValueIndex = sCookieValue.indexOf("=") + 1; sCookieValue = sCookieValue.substring(iCookieValueIndex, sCookieValue.length); indexFinCookie = sCookieValue.indexOf(" "); if (indexFinCookie != -1) { sCookieValue = sCookieValue.substring (0, indexFinCookie); } sCookieValue = unescape(sCookieValue); return sCookieValue; } var valueCookieName=getValeurCookie("name"); if(valueCookieName=""); { } var valueCookieFirstName=getValeurCookie("firstname"); if(valueCookieFirstName=""); { } var valueCookieColor=getCookieValue("color"); if(valueCookieColor=""); { } </SCRIPT> </head> <body> <form name="nameFirstName"> <table> <tr> <td valign="top"> First Name : <input type="text" name="firstname" value=""> </td> </tr> <tr> <td valign="top"> Name : <input type="text" name="name" value=""> </td> </tr> <tr> <td valign="top"> What is your favorite color? : </td> <td> <input name="white" type="radio" value="white">white<br> <input name="blue" type="radio" value="blue">blue<br> <input name="green" type="radio" value="green">green<br> <input name="red" type="radio" value="red">red<br> <input name="yellow" type="radio" value="yellow">yellow<br> <input name="purple" type="radio" value="purple">purple<br> </td> </tr> <tr> <td> <input type="button" name="bouton" Value="Submit" onClick="" > </td> </tr> </table> </form> </body> </html> The second code is the part of the greeting message that shows a different greeting message depending on the time (ex.: Good morning "Firstname name", welcome to my site (if it's morning)). The tricky thing is I can't seem to figure out how to input it in the coding. Do I need to make another file and then SRC it? 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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script type="text/javascript"> var now = new Date(); var hrs = now.getHours(); var msg = ""; if (hrs > 0) msg = "Mornin' Sunshine!"; // REALLY early if (hrs > 6) msg = "Good morning"; // After 6am if (hrs > 12) msg = "Good afternoon"; // After 12pm if (hrs > 17) msg = "Good evening"; // After 5pm if (hrs > 22) msg = "Go to bed!"; // After 10pm alert(msg); </script> </head> <body> </body> </html> I was wondering if anyone could shed some light on this little problem. Code: function lostfocus(current,productNum,e) { var keycode; if (window.event) { keycode = window.event.keyCode; } else if (e) { keycode = e.which; } if(keycode == 0) { if(current == ($("#itemCount"+productNum).val()-1)) { newItem(productNum); } } else { alert(keycode); } } Works great in FireFox, but not in IE7 - it doesn't even get to the else alert statement. This is how it is called.. onkeypress='lostfocus($current,$productNum,event)' And that is inside of a input type=text element. And help would be greatly appreciated. I am having an issue with my foor loop count-controlled input in Javascript. My code works, however, it does not allow three different users to enter three different values, instead it repeats what one user enters twice. ... Any suggestions? Thanks! CODE is below.... var hours; var rate; var tax; var gross; var deduction; var empl; var numEmpl; var accumulator; totalNet = 0; totalGross = 0; var hours = prompt("How many hours have you worked?", "") while ((hours < 0) || (hours > 80)); document.write("Total Hours: " + hours,("<br />")); var rate = prompt("What is your pay rate?", "") while ((rate < 7.50) || (rate > 15)); document.write("Pay Rate: $" + rate,("<br />")); gross = hours * rate; document.write("Gross Pay: $" + gross,("<br />")); if (hours < 40) { taxRate = .15 / 10; } else { taxRate = .30 / 10; } deduction = taxRate * gross document.write("Deduction: $" + deduction,("<br />")); net = gross - deduction document.write("Net Pay: $" + net,("<br />")); for (count = 1; count < 4; count ++) { document.write("Employee # " + count, " worked " + hours, " hours at $", + rate, " per hour for gross pay of $ ", + gross, " and net pay of $ ", + net, " based on a tax rate of ", + taxRate * 1000, "%", ("<br />")); count++; totalNet+= parseInt(net); totalGross+= parseInt(gross); } document.write("Total gross pay is: $" + totalGross, ("<br />")); document.write("Total net pay is: $" + totalNet, ("<br />")); When I enter the data into my form then submit it, it is supposed to be inserted into my MySql database but I get the following error: "Unable to save data to database: Incorrect date value: '3-31-2001' for column 'sent_date' at row 1" The sent_date field is the first date field the user types in. The TYPE for this field in the MySql database is set to DATE. Any ideas what is going on? I think the problem is in my javascript but can't find the problem... _________________________________________________________ Below is the javascript code _________________________________________________________ <script type="text/javascript"> var valid; function dcheck(form) { var a = form.assgn_date.value; var s = form.sent_date.value; var i = form.interv_date.value; var dr = form.due_rev.value var su = form.due_suspo var clk = form.due_clerk var att = form.due_attny var jdg = form.due_judge var assn = new Date(a); var sent = new Date(s); var intv = new Date(i); var due_rev = new Date(dr); var due_suspo = new Date(su); var due_clerk = new Date(clk); var due_attny = new Date(att); var due_judge = new Date(jdg); if (isNaN(sent)) { sent = new Date(assn.getFullYear(),assn.getMonth(),assn.getDate()-7); } if (isNaN(due_rev)) { due_rev = new Date(sent.getFullYear(),sent.getMonth(),sent.getDate()-42); } if (isNaN(due_suspo)) { due_suspo = new Date(sent.getFullYear(),sent.getMonth(),sent.getDate()-40); } if (isNaN(due_clerk)) { due_clerk = new Date(sent.getFullYear(),sent.getMonth(),sent.getDate()-38); } if (isNaN(due_attny)) { due_attny = new Date(sent.getFullYear(),sent.getMonth(),sent.getDate()-36); } if (isNaN(due_judge)) { due_judge = new Date(sent.getFullYear(),sent.getMonth(),sent.getDate()-7); } form.sent_date.value = (sent.getMonth()+1) + "-" + sent.getDate() + "-" + sent.getFullYear(); form.due_rev.value = (due_rev.getMonth()+1) + "-" + due_rev.getDate() + "-" + due_rev.getFullYear(); form.due_suspo.value = (due_suspo.getMonth()+1) + "-" + due_suspo.getDate() + "-" + due_suspo.getFullYear(); form.due_clerk.value = (due_clerk.getMonth()+1) + "-" + due_clerk.getDate() + "-" + due_clerk.getFullYear(); form.due_attny.value = (due_attny.getMonth()+1) + "-" + due_attny.getDate() + "-" + due_attny.getFullYear(); form.due_judge.value = (due_judge.getMonth()+1) + "-" + due_judge.getDate() + "-" + due_judge.getFullYear(); return true; } </script> I've having a problem with alignment on my portfolio. It works in mozilla although you may need to refresh the page, and it doesn't work in chrome at all. does anyone know why? the address is townsendwebdd.com thanks, I am totaly stuck Hello, Take a look at this page and this just what I want: http://yensdesign.com/tutorials/popupjquery/ But I have two issues concerning this: 1)I am able to insert a youtube image into the popup BUT when I click on the 'X' the popup disappears but the audio remains.What I would like to do is somehow alter the code so the popup is "destroyed" and the clip is stopped completely including the audio. 2) I also want to able to adapt the code so that I can click on any one of multiple youtube links and get the same effect. My javascript capabilities aren't that strong so any help or links to other pages or suggestions are welcome. |