JavaScript - If..else..if..else Statements Using Form Values As Conditions
Hey all,
Okay, Here is what i would like to do. I have a calculator he http://www.nico-online.co.uk/calculator/calc1.html which after some help from Dormilich - got working! Now, I would like to set up some conditions, so if the use selected 'Mountainbike' then, the script will perform a different calculation to if they select the 'Rennrad' option. Okay, so I was thinking an If..else..if..else statement would probably be best after reading up This is what I have come up with: Code: <script language="JavaScript"> function Framesize() { var a = parseFloat(BikeSizer.Insleg.value); if(BikeSizer.Biketype.value = "Mountainbike") { b = (a * 0.572); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 0.226); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } else if (BikeSizer.Biketype.value = "Trekking-, Reise- oder Cityrad") { b = (a * 5); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 5); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } else{ b = (a * 10); c = Math.round(b); BikeSizer.FramesizeCM.value = c; d = (a * 10); e = Math.round(d); BikeSizer.FramesizeInch.value = e; } } </script> So, I'm not too sure if I can set the Menu values as recongnisable values! Here are the values I have: <select name="Biketype" style="font-size:11px;"> <option>Mountainbike</option> <option>Trekking-, Reise- oder Cityrad</option> <option>Rennrad</option> </select> Anyone out there offer any insight? Am I going horribly wrong somewhere? Apologies for the stupidness , I am quite new to JS! Thanks in advance Similar TutorialsHiya, Not sure how to put this, here goes: I'm trying to create a form to receive customer complaints. I'm fine with the basic form structure, but would like a drop-down box or radio buttons allowing the user to state which country in the UK they are emailing from. The options are, England, Scotland, Wales and N Ireland. For example, a user fills a form in with their complaint, and selects Scotland from the drop-down/radio buttons. When the users clicks on the submit button, the script should then send an acknowledgement email to the user, and send the form details of the user to the Scottish email address of the organisation. Likewise for England, Wales and N Ireland. I'm looking at doing this all client-side. Any help would be gratefully appreciated. Many Thanks Snarf1974 I have a order form page and on submitting it opens a new web page that displays the order totals. Below is my code and most probably wrong but for me it seems logic. Please assist. Order Form: Code: <td colspan="1" height="120" align="left"> <select style="margin-left: 60px; background-color: #00FF77;" name="prod_bed_359" onchange="calculateValue(this.form)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> R359</td></tr> New page I called a unction to print: Code: function itemsOrdered() { var beds = document.forms[2].prod_bed_359.value; document.write("<pre><strong>Description\t\tQuantity\tPrice</strong></pre>"); document.write("<pre>Doggie Bed\t\t" + beds + "</pre>"); } This is still basic as I need to get this right before adding the prices and totals which is also extracted from the order page. I want to be able to load a different background image depending on the time of day. I have the code below which does work for nanaimo-morning image if before 8 am and after 8 am it will load the nanaimo-daytime image. I have tried but I can't seem to add another condition where after 8 pm it will load another imaged called nanaimo-night.png Yes, I am rather new at this, any help is greatly appreciated <code> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Untitled Document</title> <script language="JavaScript"> function determineBackground() { var currentTime = new Date(); if (currentTime.getHours() < 8) { document.body.background = 'images/nanaimo-morning.png'; } else { document.body.background = 'images/nanaimo-daytime.png'; } } </script> </head> <body onload="determineBackground()"> </body> </html> </code> FYI: THIS IS NOT HOMEWORK! Hi all, I am trying to make an all-in-one function that can use local storage and provide 4 functions: (1) read data (2) write data (3) erase specific data (4) erase all data Here's the code block I have (with alerts in place of the local storage code for debugging): Code: var storage = function (name, value) { if (name) { if (value === null) { return alert('erase'); } else { if (value != null) { return alert('write'); } else { return alert('read'); } } } else { return alert('nuke'); } }; I want to use it like this: storage(); - erases ('nukes') everything storage('abc'); - reads data stored as 'abc' storage('abc', 'newvalue'); - stores 'newvalue' as 'abc' storage('abc', null); - erases data stored as 'abc' only It seems to work, but I have a funny feeling about trusting the difference between "==" and "===" to make it work. Am I wrong? Is there a real difference between == and === and am I doing this correctly? Thanks! -- Roger Hi! I am trying to check and see if three fields are empty and if they are then to alert the user saying to fill in one of the three fields. I tried this: Code: if (StreetNumber.value.length == 0) { if (StreetName.value.length == 0) { if (City.value.length == 0) { alert("Please enter a street number, street name, or city."); StreetNumber.focus(); return false; } } } and this: Code: if (StreetNumber.value.length == 0 && StreetName.value.length == 0 && City.value.length == 0) { alert("Please enter a street number, street name, or city."); StreetNumber.focus(); return false; } Neither one works. Not sure what I am doing wrong. Thanks in advance! Never mind. I found a solution to get it working. I still don't know why it occurred, but I don't have the time to fulfill my curiosity like I could when I was a teenager. Hi I have the following code. What I want to do is for certain questions to remain hidden inless certain conditions are met, then they appear to be answered. I am thinking with the <div> but not sure how. I also thought maybe with css but cant write a if statement in css so that a no go. Please help. Code: <tr><td align="left">Do you own a Yorkie?<br /> <input type="radio" name="owner" value="yes" /> Yes <input type="radio" name="owner" value="no" checked="checked" /> No<br /> <!-- If answer is no above the below questions are hidden, if yes then they appear -->> <div id="breeders"> How many? <select name="qnty" size="1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5+</option></select> Are you a breeder? <input type="radio" name="breeder" value="yes" checked="checked" /> Yes <input type="radio" name="breeder" value="no" /> No</div></td></tr> JavaScript Code: I am using a onload within the form opening tag Code: function showDiv() { if(document.forms[2].owner.value == "yes") { document.getElementById('breeders').style.visibility = 'visible'; } else document.getElementById('breeders').style.visibility = 'hidden'; } Hi I am trying to write a JavaScript conditional statement for 4 conditions I currently have: Code: var teamId=obj.id.substring(0, 1); var indx=obj.id.substring(obj.id.indexOf('_')+1); var id=indx.substring(0, indx.length-1); var anotherTab = (indx.indexOf('a') >= 0) ? id + 'b' : id + 'a'; var anotherTab2 = (indx.indexOf('c') >= 0) ? id + 'b' : id + 'c'; var anotherTab3 = (indx.indexOf('d') >= 0) ? id + 'b' : id + 'd'; document.getElementById(teamId+'tab_' + indx).className = 'selected'; document.getElementById(teamId + 'tab_' + anotherTab).className = ''; document.getElementById(teamId + 'tab_' + anotherTab2).className = ''; document.getElementById(teamId + 'tab_' + anotherTab3).className = ''; if (indx==id+'a') { show (teamId+'basketballInfo_'+id); hide(teamId + 'soccerInfo_' + id); hide(teamId + 'footballInfo_' + id); hide(teamId + 'baseballInfo_' + id); } else if(indx==id+'b') { hide(teamId + 'basketballInfo_' + id); show(teamId + 'soccerInfo_' + id); hide(teamId + 'footballInfo_' + id); hide(teamId + 'baseballInfo_' + id); } else if(indx==id+'c') { hide(teamId + 'basketballInfo_' + id); hide(teamId + 'soccerInfo_' + id); hide(teamId + 'baseballInfo_' + id); show(teamId + 'footballInfo_' + id); } else { hide(teamId + 'basketballInfo_' + id); hide(teamId + 'soccerInfo_' + id); hide(teamId + 'footballInfo_' + id); show(teamId + 'baseballInfo_' + id); } } I am trying to turn one tab on and have the others turned off until another tab is clicked on. It works fine if I have all 4 conditions but I need to be able to also have 3, 2, and 1. What would be an easy way to do so? Hi, The following code is supposed to display and hide fields when clicking on radio buttons which is does correctly, it also gives the fields that are hidden a value so that it passes validation. T The problem is that when the user moves from one field to the next, it deletes the value that they have just entered. :S Any ideas why this might occur? Thanks! Code: <script language="javascript" type="text/javascript"> function showHideDivs(){ var category = ''; for(i=0; i < oRadBtns.length; i++){ if(oRadBtns[i].checked){ category = oRadBtns[i].value; } } switch (category){ case 'empresa': document.getElementById("empresa_nombre").value = ""; document.getElementById("contacto").value = ""; document.getElementById("nombre").style.display = "none"; document.getElementById("apellido").style.display = "none"; document.getElementById("company").style.display = "block"; document.getElementById("contact").style.display = "block"; document.getElementById("firstname").value = "nombre"; document.getElementById("lastname").value = "apellido"; break; case 'particular': document.getElementById("firstname").value = ""; document.getElementById("lastname").value = ""; document.getElementById("nombre").style.display = "block"; document.getElementById("apellido").style.display = "block"; document.getElementById("company").style.display = "none"; document.getElementById("contact").style.display = "none"; document.getElementById("empresa_nombre").value = "empresa"; document.getElementById("contacto").value = "contacto"; break; } } window.onload=function(){ oRadBtns = document.getElementById('dmsfrm').getElementsByTagName('input'); for(i=0; i < oRadBtns.length; i++){ oRadBtns[i].onclick = showHideDivs; } showHideDivs(); } </script> Code: <div class="radio_element"> <input type="radio" value="empresa" class="radio" id="empresa" name="categoria" <?php echo ($leadsEngine->getElementValue('categoria')!='particular')?'checked="checked"':'' ?> /> <span class="<?PHP if($leadsEngine->hasError('categoria')){echo 'error';} ?> ">Empresa</span> </div> <div class="radio_element"> <input type="radio" value="particular" class="radio" id="particular" name="categoria" <?php echo ($leadsEngine->getElementValue('categoria')=='particular')?'checked="checked"':'' ?> /> <span class="<?PHP if($leadsEngine->hasError('categoria')){echo 'error';} ?> ">Particular</span> </div> </div> Greetings I have a textarea on my page and I wonder if its possible for a visitor to type in something in the textarea and then it will store in XML is it possible? Best Regards Obsivus Hi, I have a form where dob is generated using 3 select boxes, 1 for day, month and year. My output needs to be in the form dob=dd-mm-yyyy rather than day=dd, month=mm and year=yyyy. It has been suggested that i do the following: "On submit button click, use JS to create a hidden input (Q5) in the form and assign its value, then disable the day, month, and year fields so they are not submitted." Does anyone know how to do this? Hi there, I'm absolute newbie in javascript, so the question may look not worth asking for you. Sorry for that. My situation is like that: I want to make a preview of form data using javascript. After the button "preview" is clicked I start showing div dialog which should contain data entered by users. The problem is that because my div dialog is coded in the same page as form I can get only default values. It means - after making some changes, they are not visible. To get and print the value of input I use this code: Code: <script type="text/javascript"> mytext = document.getElementById('name').value; document.write(mytext); </script> How it would be possible to update the values on "on click" event. Thank you very much for considering this question. I have 4 text boxes that are supposed to load 4 seperate values of data from one field in one table from a database. The field is called interface_cropsettings (from the interface table) and these values have been concatenated and comma seperated in this field. Code: <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceXPosition" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceYPosition" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceCropHeight" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> <TR> <TD WIDTH="350" CLASS="tabledata"><INPUT TYPE="TEXT" SIZE="55" NAME="txtInterfaceCropWidth" maxlength="10" <CFIF IsDefined("isEdit")>VALUE="#qryEditInterface.interface_cropsettings#"></CFIF></TD> </TR> Once the form is filled out and saved, the data is inserted into the database and the values from these 4 text boxes are concatenated, comma seperated and inserted into that one field correctly. (Example) If the 4 text boxes have the following values: X Position = 12.34 Y Position = 56.78 Crop Height = 250 Crop Width = 500 in the database field they become: 12.34,56.78,250,500 However, if the form is closed and then re-opened, each text box displays the entire database field rather then each value seperated in the corresponding text box. (Example) All 4 text boxes display this: 12.34,56.78,250,500 I already know why the data appears like this in the form, my problem is that I'm not sure how to write the javascript to seperate the values into the correct corresponding fields, assuming javascript is what I should be using! Can anyone help me out with this?? Also, this is kind of irrelevant but just in case you're wondering, this form is part of a cold fusion application! Hi, I'm having a bit of trouble with this here... Before I submit the form with JS I update an input field with js like this: Code: Code: document.getElementById('IC_Checksum').value = data; imaginaryform.submit(); The problem is that the updated value is not sent along with the post data. Instead the old value is sent along. When i submit the form with a button afterwards though (not auto submit after the value is set), then the value is sent along fine. But that's not how I want it to work... Can anyone tell me how I can send the value that I'm setting with JS along with the post data like this? I am having some trouble trying to fix my math equation to calculate the total rent by aquiring values from my form fields. Converting the date fields to days and finding the number of days via two date fields is mainly where I am having trouble. Also, I am trying to have a window pop up before submission but the onclick event does not seem to function properly. Any suggestions would be greatly appreciated. Thank you. Below is the math equation I have come up with: Code: //calculate days from date field function calcTotal(date1, date2) { //assign variables var equip = parseFloat(document.forms[0].equipment.value) var pDate = parseFloat(document.forms[0].pickupDate.value) var pHours = parseFloat(document.forms[0].pickupHours.value) var pMinutes = parseFloat(document.forms[0].pickupMinutes.value) var rDate = parseFloat(document.forms[0].returnDate.value) var rHours = parseFloat(document.forms[0].returnHours.value) var rMinutes = parseFloat(document.forms[0].returnMinutes.value) // The number of milliseconds in one day var ONE_DAY = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1_ms = rDate.getTime() var date2_ms = pDate.getTime() // Calculate the difference in milliseconds var difference_ms = Math.abs(date1_ms - date2_ms) //calculate total cost and diplay in window.confirm() dialog box var pTime = pHours + pMinutes; var rTime = rHours + rMinutes; var total = (((difference_ms/ONE_DAY) - 1) * 24) * equip + ((rTime + (24 - pTime)) * equip); var OK = window.confirm(" The total rental cost is $" + total + "\n Click OK to accept, Cancel to decline"); if (OK) {return true} else {return false} } Below is the body section of the form: Code: <input type = "submit" name = "submit" value = "Submit Reservation" onclick = "calcTotal()"/> Hello, I have a form that works out some basic math questions e.g. area etc. I run a function when a form field is updated to do the calculations, however I'd like to run a different calculation depending on which form element was updated. Is there a way to say something like: if (area1 was updated) { work out this calculation } if(area2 was updated) { work out this calculation } and so on? Thanks, Nicola I want to loop through a form containing various fields and replace them with values I have in a JS object. E.g. (1) <form id="theform"> <input type="text" name="field_1" value="" /> <input type="checkbox" name="field_2" value="" /> </form (2) object.field_1 = "Dave"; object.field_2 = ""; // empty as not checked, else holds value of checked one -- The problem is: what about checkboxes and <select> drop downs, and radios?? Is there a script like this around as I'm guessing this could be useful for Ajax to populate input boxes in some situations (depending on the content etc.) so I'm guessing I'm not the only one who needs this? This form collects info of the customer who wishes to select add-ons that would be applied to their digital photos. Examples of add-ons: Photo makeover Add object or person Crop image Have a look at the form Once a customer selects one of the options (Photo Manipulation or Photo Restoration for example - radio buttons) and then one or more Add-ons (check boxes in the Html form), enter their details and upload a photo, they hit the submit button and it then takes them to the PayPal checkout page where the total amount is shown. (see image below) The Issue: In the PayPal page, it now shows the total amount whichever add-ons you select, however it keeps showing "Add object or person" as well as all the 5 main options (radio buttons on the form) no matter what I select. This will be an issue as I will not know exactly which add-ons the customer has selected. Can someone please help me complete the coding so that the add-ons show on the PayPal checkout page. I look forward to your reply/replies. Kind Regards Rafi p.s: Could this be a possible solution? Even if it is, can someone help by completing the code? In order to send the options/add-ons the customer selects I may need to use the onX and osX variables (Where X is a number starting with 0 and incrementing by 1 see below), These can be used to set options for the add-onsthey select. The onO is the "option name" and os0 is the "option choice". So for example: <input type="hidden" name="on0" value="Photo manipulation"> <input type="hidden" name="os0" value="Whatever add-ons the customer selects"> <input type="hidden" name="on1" value="Photo restoration"> <input type="hidden" name="os1" value="Whatever add-ons the customer selects"> |