JavaScript - Having Trouble Directing Output From A Form
Hey guys, I am pretty new at javascript but am trying to learn.
Here is a problem I have encountered. I have made a form with various input fields and a set of radio buttons which change the parameters of the form. One of the radio button sets is "Search by X" and "Search by Y" I want the action parameter for the form to change depending on whethere X or Y is selected Code: <FORM name=ENTRY_FORM onSubmit="return Check();" action="pointMeTo()" method="get"> If X is selected then action="http://site.com//doSomething.action" if Y is selected then action="http://site.com//doSomethingElse.action" The way I attempted to do the above(and I am not claiming this to be most efficient, just what comes to mind at the moment) is to create three functions and two global variables. Code: var xyToggler = false; var out = ""; function toggleX(){ xyToggler = false; } function toggleY(){ xyToggler = true; } function pointMeTo(){ if(xyToggler){ out="http://site.com//doSomething.action" } else out="http://site.com//doSomethingElse.action" } Thats the javascript part, now on the html form part: Code: <FORM name=ENTRY_FORM onSubmit="return Check();" action="pointMeTo()" method="get"> <!-- Stuff --> <input type="radio" name="choose" id="X" NAME="rbXY" value="X" onClick="toggleX()" checked/><label for="X">X</label> <input type="radio" name="choose" id="Y" NAME="rbXY" value="Y" onClick="toggleY()" /><label for="Y">Y</label> The logic seems like it would work to me, but when I try it out the results that are expected to come depending on the parameters X or Y are not displayed, in fact nothing is displayed but a msg saying that there is no such link. So I am assuming that means that the function is not properly assigning the corresponding links to the action= field in the form. Many thanks to whoever can spot my error or give me some advise! All the best. Similar TutorialsHey. I need some javascript help. Quite confused. So I made a .js file with the following contents. function cost (){ var q = "How much do you want to spend for a Hotel?" var newb1 = prompt(q, "") var q = "How much do you want to spend for Food?" var newb2 = prompt(q, "") var q = "How much do you want to spend for Activities?" var newb3 = prompt(q, "") var q = "How much for Shopping?" var newb4 = prompt(q, "") sum2 = parseInt(newb1) + parseInt(newb3) + parseInt(newb4) document.getElementById("cost").innerHTML = "Total Price :" +sum2 } Then I inserted it into my homepage using this. <script type="text/javascript" src="hotelprice.js"></script> The prompt comes up, asks for all of the inputs. But it doesn't display the output, which should have simply added them all together. How do I fix this? I have an array, I can not figure out how to take myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>");} to display to separate lines. Right now, if there is more than one value, it gets added together. Here's the rest of the code: Code: function showText(){ // var myTemplateholder = document.getElementById('myTemplateholder').innerHTML; // document.getElementById('showMe').innerHTML = myTemplateholder; var children = new Array('Chills','Fatigue','Fever','Health History','Screening','Eye-ROS','Skin','Assessment','General Appearance','Vitals','Hearing','200','300','400','500'); var myTemplateholder = $('#myTemplateholder').text(); myTemplateholder = myTemplateholder.replace("Sections ",""); myTemplateholder = myTemplateholder.replace("History","<div id='templateHeader'>History</div>"); myTemplateholder = myTemplateholder.replace("ROS","<div id='templateHeader'>ROS</div><br>"); myTemplateholder = myTemplateholder.replace("Exam","<div id='templateHeader'>Exam</div>"); myTemplateholder = myTemplateholder.replace("ICD9","<div id='templateHeader'>ICD9</div>"); for(child in children) { myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>"); } $('#showMe').html(myTemplateholder); } I'm totally stuck! Thanks for bearing with a newbie - any help would be greatly appreciated. Hi guys, I am new to Javascript and I'm trying to set up a form to make simple calculation based on user inputs. I have set up the form and am unable to get the calculation to work despite what I try (this is based on an online tutorial I found though). Is there any where I am going wrong? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" language="javascript"> function kanban() { //variables A = document.frmone.annualdemand.value; B = document.frmone.demandVariability.value; C = document.frmone.weeksHold.value; D = document.frmone.ContainerSize.value; E = document.frmone.totalStock.value; //calculation F = A/240; double G = (b/100)+1; H = g*F; c = c*5; i = c*H; j = i/d; document.frmone.totalStock.value = i; document.frmone.noKanBans.value = j; } </script> <title>Insert Title Here</title> </head> <body> <form name="kanban" id="frmone"> Annual Demand: <input type="text" name="annualDemand" value=""/> </br> Demand Variation: <input type="text" name="demandVariability" value=""/> </br> Stock to Hold (weeks): <input type="text" name="weeksHold" value=""/> </br> Size of Container: <input type="text" name="containerSize" value=""/> </br> </br> <input type="button" name="calculate" value="Calculate" onclick="kanban()"/> </br> </br> Total Stock: <input type="text" name="totalStock" value=""/> </br> Qty of Kan Bans: <input type="text" name="noKanBans" value=""/> </br> </form> </body> </html> Thanks guys. Hi does anyone know how to output a reformated number to a form?? This is what I have so far: Code: if (!document.userSurvey.phone.value) { alert("Phone number missing. Please enter a valid phone number to continue."); document.userSurvey.phone.focus(); return false; } else { var numbersOnly = ""; var chars = ""; var phoneNo = document.userSurvey.phone.value; for (i = 0; i < phoneNo.length; i++) { chars = phoneNo.substring(i,i+1); if (chars >= "0" && chars <= "9") { numbersOnly = numbersOnly + chars; } } if (numbersOnly.length != 13) { alert("Incorrect phone number format.You must enter 13 numbers."); document.userSurvey.focus(); return false; } else { var areacode = numbers.substring(0,2); var leading0 = numbersOnly.substring(2,3); var exchange = numbersOnly.substring(3,5); var ext1 = numbersOnly.substring(5,9); var ext2 = numbersOnly.substring(9); var newNumber =( "+" + areacode + " " +"(" + leading0 + ")" + exchange + " " + ext1 + "-" + ext2); Hey everyone. I hope you can help me getting through this problem, because I have no idea of what else to try. I'm a web designer and sometimes modify Javascript, but my main focus is HTML and CSS, meaning I have no idea how to code in Javascript or how to write something from scratch in PHP. So I designed a form that works pretty well, and integrated a PHP and Javascript script to make it work. This is the form: Code: <form name="form" id="form" method="post" action="contact.php"> <p>Hello,</p> <p>My name is <input type="text" name="name">, from <input type="text" name="location">, and I'd like to get in touch with you for the following purpose:</p> <p><textarea name="message" rows="10" ></textarea></p> <p>By the way, my email address is <input type="text" name="email" id="email" placeholder="john@doe.com">, and I can prove I'm not a robot because I know the sky is <input type="text" name="code" placeholder="Red, green or blue?">.</p> <p title="Send this message."><input type="submit" id="submit" value="Take care."></p> </form> And this is the script, in an external file called contact.php: Code: <?php $name = check_input($_REQUEST['name'], "Please enter your name.") ; $location = check_input($_REQUEST['location']) ; $message = check_input($_REQUEST['message'], "Please write a message.") ; $email = check_input($_REQUEST['email'], "Please enter a valid email address.") ; if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {die("E-mail address not valid");} if (strtolower($_POST['code']) != 'blue') {die('You are definitely a robot.');} $mail_status = mail( "my@email.com", "Hey!", "Hello,\n\n$message\n\nRegards,\n\n$name\n$location", "From: $email $name" ); function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); if ($problem && strlen($data) == 0) { show_error($problem); } return $data; } function show_error($myError) { ?> <html> <body> <b>Please correct the following error:</b><br /> <?php echo $myError; ?> </body> </html> <?php exit(); } if ($mail_status) { ?> <script language="javascript" type="text/javascript"> alert('Thank you for the message. I will try to respond as soon as I can.'); window.location = '/about'; </script> <?php } else { ?> <script language="javascript" type="text/javascript"> alert('There was an error. Please try again in a few minutes, or send the message directly to aalejandro@bitsland.com.'); window.location = '/about'; </script> <?php } ?> So what it does is this: if everything's OK, it sends an email with "Hey!" as the subject, "[name]" as the sender, "Hello, [message]. Regards, [name], [location]" as the body, and a popup saying the message was delivered appears. If something fails, it outputs the error in a new address, so the user will have to go back to the form and correct the error. What I actually want to happen is this: if everything's OK, a <p> which was hidden beneath the form appears saying the message was delivered, or, alternatively, make the submit button gray out and confirm the message was delivered. I found a script to make this happen, but with "Please wait...", so the user can't resubmit the form. If there's an error, I'd like another <p> which was hidden to appear with the specific error, so there'd be many <p>'s hidden with different IDs. If possible, I'd also like to change the CSS style of the input field, specifically changing the border color to red, so it'd be a change in class for the particular field. -- So in essence, I want the errors and the success messages to output in the same page as the form (without refresh), and a change of class in the input fields that have an error. It'd be great if the submit button could be disabled until all fields are filled correctly, but I don't know if this is possible. Thanks in advance, and please let me know if it'll be possible. :) Can someone help me I am trying to get these two values, firstname and lastname to both go into the same output box on a form. I want them to show up alongside one another like so nameform.output2.value=firstname + " " + lastname; but the values are assigned within seperate if statements as you can see below.. so I dont know how to get them to merge.. I am kinda new with javascript so any help will be very useful. Thakns very much. Code: function checkform(nameform){ var firstname=new Array(); firstname[0]="johndefinition"; firstname[1]="jamesdefinition"; var lastname=new Array(); lastname[0]="smithdefinition"; lastname[1]="simpsondefinition"; if (document.getElementById("namebox").value.indexOf("John")!=-1) {nameform.output2.value= firstname[0];} if (document.getElementById("namebox").value.indexOf("James")!=-1) {nameform.output2.value= firstname[1];} if (document.getElementById("namebox").value.indexOf("Smith")!=-1) {nameform.output2.value=lastname[0];} if (document.getElementById("namebox").value.indexOf("Simpson")!=-1) {nameform.output2.value=lastname[1];} } Hi ! i sometimes are able to alter simple javascript, but i need help with the following. MaxMind.com has a javascript or geotargetting. It displays the country where ur at. I need this output in a form, so i can store it in a database. this is the script i use: <script language="JavaScript" src="http://j.maxmind.com/app/country.js"></script> <br>Country Code: <script language="JavaScript">document.write(geoip_country _code());</script> <br>Country Name: <script language="JavaScript">document.write(geoip_country _name());</script> How can i get the country name to be displayed in an input field ? something like: <form name="xx" action="somepage.htm" method="post"> <input type="Text" size="50" name="country" value="country name"> </form> my password target opens in a new window using the 'open.window' command but i would like a command string that opens this target in the same frame within my frames page that my other pages open in. thanks in advance manj I have a form that I've made in the XHTML comprised of text boxes and radio buttons. I want to put a button on the page that when clicked, takes the values in the data, processes it client-side and then outputs it to the same page that it took the data from. I'm having difficulty know exactly how to reference the data in each form element. So far, it seems like I can use getElementById, but my efforts so far have stymied me. The code is this: 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> <title>QuadWay DomQuote</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <!-- external script declarations --> <script type="text/javascript" src="chkValidityOfNumber.js"></script> <script type="text/javascript" src="calcQuote.js"></script> <script type="text/javascript" src="calcGoodsAndServicesTax.js"></script> <script type="text/javascript" src="calcTotalCostIncludingGST.js"></script> <script type="text/javascript" src="outPutResultsToPage.js"></script> </head> <body> <form action="" name="quadway"> <!-- create fields to enter customer details into --> <b>Customer Details</b> <p>Customers Full Name: <input type="text" id="customersfullname" name="custName" /> </p> <p>Contact Telephone Number: <input type="text" id="customerstelephonenumber" name="phoneNumber" /> </p> <p>Customers Address: <textarea id="customersaddress" name="custAddress" cols="20" rows="5"></textarea> </p> <hr /> <!-- create fields to enter the regularity of service --> <b>Regularity</b> <p> <input type="radio" name="regularity" value="1" /> Once only </p> <p> <input type="radio" name="regularity" value="4" checked /> Weekly </p> <p> <input type="radio" name="regularity" value="2" /> Fortnightly </p> <p> <input type="radio" name="regularity" value="1" /> Monthly </p> <hr /> <!-- create radio buttons to select the contract period --> <b>Contract Period</b> <p> <input type="radio" name="contractperiod" value="1" /> N/A (Once Only) </p> <p> <input type="radio" name="contractperiod" value="6" /> Six Months </p> <p> <input type="radio" name="contractperiod" value="12" /> One Year </p> <p> <input type="radio" name="contractperiod" value="24" /> Two Years </p> <hr /> <!-- create radio buttons to select the type of service --> <b>Type</b> <p> <input type="radio" name="typeOfService" value="1" /> Standard </p> <p> <input type="radio" name="typeOfService" value="1.4" /> Premium </p> <hr /> <!-- create fields to enter how many bedrooms, living areas and service areas there are and their area --> <b>Bedrooms</b> <p>Number of bedrooms: <input type="text" name="numBedrooms" size="3" maxlength="3" onchange="return chkValidityOfNumber(this)" /> </p> <p>Area: <input type="text" name="areaBedrooms" size="3" maxlength="3" onchange="return chkValidityOfNumber(this)" /> m2 </p> <b>Living Areas</b> <p>Number of living areas: <input type="text" name="numLivAreas" size="2" maxlength="3" onchange="return chkValidityOfNumber(this)" /> </p> <p>Area: <input type="text" name="areaLivAreas" size="3" maxlength="3" onchange="return chkValidityOfNumber(this)" /> m2 </p> <b>Service Areas</b> <p>Number of service areas: <input type="text" name="numServAreas" size="2" maxlength="3" onchange="return chkValidityOfNumber(this)" /> </p> <p>Area: <input type="text" name="areaServArea" size="3" maxlength="3" onchange="return chkValidityOfNumber(this)" /> m2 </p> <input type="button" name="calculateQuoteButton" value="Calculate Quote" onClick = "calcQuoteBeforeTax(this.form)"></input> var theForm=document.getElementById("quadway"); <input type="button" name="tester" value="test" onClick = "alert(document.quadway.getElementById.elements[0].value);"></input> </form> <hr /><hr /> <b>Quote</b> </body> </html> Right down the bottom, under the word 'Quote is where the output should go. Any suggestions on how to do this? Regards Jenny I am trying to submit my form and receive a success message that go's away. My form validation is working fine and I receive the email, but the echo back to json is giving my error message instead of my success message. This is my first try doing this and am brand new to javascript. If anyone could please help me figure out what is wrong or tell me how to rewrite it, I would be much obliged. Code: function submitForm(formData) { $.ajax({ type: 'POST', url: 'bookings.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success') .html(data.msg).fadeIn('fast'); if ($('form #response').hasClass('success')) { setTimeout("$('form #response').fadeOut('fast')", 5000); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('form #response').removeClass().addClass('error') .html('<strong>There was an error. Please use the above information and contact us directly.</strong>').fadeIn('fast'); }, complete: function(XMLHttpRequest, status) { $('form')[0].reset(); } }); }; Hello, i got a problem with form like this: https://www2.giocarena.com/it-IT/Register/Start.aspx It's possible to set the field Cod Referent????? I've tried with this: <form name="aspForm" method="post" action="https://www2.giocarena.com/it-IT/Register/Start.aspx" target="_blank"> <input type="hidden" name="ctl00$cphBaseContainer$ctl00$txt_code" value="44411122224322445"></input> <button type="submit"> Nome </button> </form> Thank you!Thank you, thank you! I have been working on this code for a few days now. It is suppose to: 1. Remove the default values placed in the textarea. 2. Enter only numbers in the Phone Number field. 3. Verify that the passwords entered in the password fields are the same. 4. Verify everything is filled out, one of the radio buttons is selected and at least one of the check boxes are checked using a Submit() function as well as clear the fields using a Reset() function. I have the first two figured out and was able to get the password to verify once but can not get it to work again with any code. I am also unable to figure out a code that will call all these funtions together in the end to verify everything is filled out and not have the default words count as the field being filled. The idea of a default text is also kind of strange to me. I figured out how to remove the text entered as the value, but how do you get JavaScript to know that is the default and not an option to be used? 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>Registration</title> <!--Create a registration form, similar to what you may encounter when registering for an online Web site. Include three sections: Personal Information, Security Information, and Preferences. In the Personal Information section, add name, e-mail address, and telephone fields. Include default text in the name and e-mail text boxes, but write some code that removes the default text from each text box when a user clicks it. Write code for the telephone field that prevents users from entering any values except for numbers. In the Security Information section, add password and password confirmation fields. Write code that ensures that the same value was entered into both fields. Also add a security challenge question selection list and a security answer text box that the Web site will use to help identify a user in the event that he or she loses his or her password. The security challenge selection list should contain questions such as What is your mother's maiden name?, What is the name of your pet?, and What is your favorite color?. In the Preferences section, add radio buttons that confirm whether a user wants special offers sent to his or her e-mail address. Also, include check boxes with special interests the user may be interested in, such as entertainment, business, and shopping. Add submit and reset buttons that call submit() and reset() event handler functions when they are clicked. The submit() event handler function should ensure that the user has entered values into each text box, and that the values submitted are not the same as the default text. The submit() event handler function should also ensure that the user selects a security challenge question, selects a radio button to confirm whether he or she wants special offers sent to his or her e-mail address, and selects at least one interest check box. Submit the form to the FormProcessor.html script (there is a copy in your Cases folder for Chapter 5). Save the document as Registration.html. --> <script language="javascript" type="text/javascript"> // This JavaScript removes default values form field function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = "" } } // This JavaScript allows characters exept numbers function AcceptLetters(objtextbox) { var exp = /[^\D]/g; objtextbox.value = objtextbox.value.replace(exp,''); } // This JavaScript allows numbers only function AcceptDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,''); } //This JavaScript confirms everything is filled out function confirmSubmit() { var submitForm = window.confirm("Are you sure you want to submit the form?"); if (document.registar[0].name.value == "Name" || document.registar[0].name.value == "" || document.registar[0].e_mail.value == "E-Mail Address" || document.registar[0].e_mail.value == "" || document.registar[0].phone.value == "" || document.registar[0].phone.value == "" || document.registar[0].password1.value == "" || document.registar[0].password2.value == "" || document.registar[0].sq_answer.value == "Question Answer") { window.alert("You must enter all fields above."); return false; } else return true; } </script> </head> <body> <h1>Registration Page</h1> <form name="registar " method="post" onsubmit="return confirmSubmit()"> <h3>Personal Information</h3> Name:<br /> <input type="text" name="name" value="Name" maxlength=10 id="letters" onFocus="doClear(this)" onkeyup="AcceptLetters(this)" /> <br /> E-Mail:<br /> <input type="text" name="email" value="E-mail Address" onFocus="doClear(this)" /> <br /> Phone Number:<br /> <input type="text" name="phoneNumber" maxlength=10 id="txttest" onFocus="doClear(this)" onkeyup="AcceptDigits(this)" /> <br /> <h3>Security Information</h3> Password:<br /> <input type="password" name="password1" /><br /> Confirm Password:<br /> <input type="password" name="password2" /><br /> <DIV ID="password_result"> </DIV> Security Question:<br /> <select id="selection"><br /> <option value=0>Please Choose One</option> <option value=1>What is your favorite food?</option> <option value=2>What is your Mother's maiden name?</option><br /> <option calue=3>What is your pets name?</option><br /> <option value=4>What is the name of your High School?</option><br /> </select><br /> Answer<br /> <input type="text" name="sq_answer" value="Question Answer" onFocus="doClear(this)" /><br /> <h3>Preferences</h3> Yes<input type="radio" name="confirmAnswer" value="Yes"/>No<input type="radio" name="answer" value="No" />Would you like any special offers sent to your E-mail address?<br /> <h5>Interests</h5> <input type="checkbox" name="interest" value="check"/>Entertainment<br /> <input type="checkbox" name="interest" value="check"/>Shopping<br /> <input type="checkbox" name="interest" value="check"/>Business<br /> <input type="checkbox" name="interest" value="check"/>Exercise<br /> <br /> <input type="submit" value="Submit"/> <input type="reset" value="Reset"/> </form> </body> </html> I'm trying to make an xhtml form that validates itself through a javascript function. I have the form up but for some reason I can't get it to validate. I'm not even sure if I linked things correctly. Here's what I have: the xhtml file <?xml version = ″1.0″ encoding = ″utf-8″ ?> <!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> <script src="gas24.js" type="text/javascript"></script> <h2> Registration Form </h2> <title> Javascript Form Validation Homework </title> </head> <body> <table border=""> <form name="validation_form" method="post" onsubmit="return validate()"> <tr> <td> <t>Name: <input type="text" name="YourName" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> E-mail Address: <input type="text" name="YourEmail" size="10" maxlength="24"/> </td> </tr> </br> <tr> <td> Password: <input type="password" name="YourPassword" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Re-Type Password: <input type="password" name="passwordConfirmed" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Your Gender: <input type="radio" name="MaleBox" Value="Male"> Male <input type="radio" name="FemaleBox" Value="Female"> Female </td> </tr> </br> <tr> <td> Comments: <input type="text" name="Comments" size="100" maxlength="500" value=""/> </td> </tr> <tr> <td> <input type="submit" value="Submit"/> </td> </tr> </form> </table> <p></p> </body> </html> The javascript file: I've tried two things. This: <SCRIPT LANGUAGE="JavaScript"> function validation() { var x=document.forms["validation_form"]["YourName"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } And this: function validation() if ( document.validation_form.YourName.value == "" ) { alert( "Please type your name."); valid = false; } if ( document.validation_form.YourPassword.value =! "document.validation_form.Confirm.value" ) { alert ( "Please confirm your password." ); valid = false; } I would greatly appreciate it if somebody could tell me what I'm doing wrong. I'm trying to create a popup sign up form that will only popup every week. I don't want it to popup every time someone visits the site. I'm new to Javascript as a whole and can't seem to figure out how to set a cookie for a week and if there is no cookie (or the cookie has expired) it will popup automatically. If anyone can point out what I'm doing wrong it would be greatly appreciated. I feel like I'm so close and that the solution is staring me in the face. Here's the code that I have so far: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + 5); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie(exdate); if (exdate!=null && exdate!="") { //Do Nothing } else { $(document).ready(function() { var id = '#dialog'; //Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Set heigth and width to mask to fill up the whole screen $('#mask').css({'width':maskWidth,'height':maskHeight}); //transition effect $('#mask').fadeIn(1000); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center $(id).css('top', winH/100-$(id).height()/2); $(id).css('left', winW/2-$(id).width()/2); //transition effect $(id).fadeIn(1000); $(id).animate({top:"+=300px"},1000); //if close button is clicked $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $('.window').animate({right:"+=150px"}).animate({left:"1500px"}).fadeOut(50); $('#mask').hide(); }); //if NO Thanks button is clicked $('.window .noThanks').click(function (e) { //Cancel the link behavior e.preventDefault(); $('.window').animate({right:"+=150px"}).animate({left:"1500px"}).fadeOut(50); $('#mask').hide(); }); //if mask is clicked $('#mask').click(function () { $(this).hide(); $('.window').hide(); }); function hideHolder() { $('.place-holder').hide(); } function showHolder() { if($('.name-field').val() == '') { $('.place-holder').show() } } $('.name-field').focus(hideHolder); $('.name-field').blur(showHolder); $('.place-holder').click(function () { $('.name-field').trigger('focus'); }); }); } } Thank you for your help. :-) Hi all, I am new to JS and usually learn by studying code posted online and modify it to have it do what I need. Recently, I used a totaling plugin for an online ordering form which does the below: item1 qty(user input text) * preset price = total price item2 qty(user input text) * preset price = total price item3 qty(user input text) * preset price = total price -------------------------------------------------------- grand total -------------------------------------------------------- The JS code which passes the grandTotal variable is as below: Code: function ($this){ // sum the total of the $("[id^=total_item]") selector var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits "₹" + sum.toFixed(2) ); } The problem I have is the above grandTotal displays the final value when put into a table like below: Code: <td align="right" id="grandTotal"></td> But I am unable to make it work by passing it into a variable within the form fields. I would like to do something like this: Code: <input type="text" name="grandTotal" id="grandTotal" readonly="readonly" /> Can somebody please help me fix this? Any help will be greatly appreciated. Thank you. Hey guys, if someone could help point me in the right direction that would be great. I cant get seem to get this array to print the numbers 1 to 15 out. When I preview I get nothing, anyone know what I am doing wrong? Thanks to those that reply. thanks got it hi, I'm a new guy to computer science and info system and I am taking an intro class to it right now. I was asked to make a simple "enter the word in the box" quiz and I can't get the output! it's driving me crazy and I get "ur score is [object HTMLInputElement]out of 3" at the bottom when I had it say, "Your score is:".. here is my html coding and no, I'm not asking for anyone to do my homework. I just want to make this work! be easy. NOTE: I'm using Apple over again because I want to get the coding down and then I will change up the quiz and the answers Code: <html> <head> <title> COMSC 100 Assignment 9 by Me </title> <script> function getInputAsText(_id){return document.getElementById(_id).value} function getInputAsNumber(_id){return parseFloat(document.getElementById(_id).value)} function setOutput(_id, _value){document.getElementById(_id).value = _value} function calculate() { // declare all variables var myResult1 var myResult2 var myResult3 var resultAsText // get variable's value myAnswer1= getInputAsText("myResult1") myAnswer2= getInputAsText("myResult2") myAnswer3= getInputAsText("myResult3") // perform concatenation if (myAnswer1.toLowerCase() == " Apple" .toLowerCase()) { score= score + 1 // got this one right myResult1= "correct" } else { myResult1 = "Wrong! It's Apple" } if (myAnswer2.toLowerCase() == "Apple".toLowerCase()) { score= score + 1 // got this one right myResult2 = "correct" } else { myResult2 = "Wrong! it's Apple" } if (myAnswer3.toLowerCase () == "Apple".toLowerCase()) { score = score + 1 //got this one right myResult3 = "correct" } else { myResult3 = "Wrong! It's Apple" } // write output value setOutput("score", "Your score is " + score + "out of 3") setOutput ("myResult1",myResult1) setOutput ("myResult2",myResult2) setOutput ("myResult3",myResult3) } </script> </head> <body> Directions:<br> Answer the three questions and press go <br> Your score will appear<br> Input values:<br> 1. A byte is how many bits?<input id="myResult1"><br> 2.Steve Jobs heads what company?<input id="myResult2"><br> 3.Bill Gates heads what company? <input id="myResult3"><br> <input type="submit" value="go" onclick="calculate()"><br> Output<br> Result #1:<input id= "myResult1" size="25"><br> Result #2:<input id= "myResult2" size="25"><br> Result #3:<input id= "myResult3" size="25"><br> Your sco <input id= "score" size="25"> </body> </html> I thought I knew how, but I'm unclear how to get this function to display: "document.getElementById("txtHint").innerHTML=xmlhttp.responseText;" inside the div. Will you show me please? Code: xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var div = document.createElement('div'); div.setAttribute('id', 'txtHint'); div.setAttribute("style","background-color:red;"); div.style.width = '300px'; div.style.height = '100px'; document.getElementById("txtHint").innerHTML=xmlhttp.responseText; //var txt='hello world!'; document.getElementsByTagName('body')[0].appendChild(div); document.getElementById('textHint').innerHTML=txt; } } |