JavaScript - Help With Adding Listbox Options To Multiple Textboxes
Hello! coding forums pals, I am resorting to you for help with a html form that uses javascript to validate data. the form is an invoice for a trip order where the user can select a trip location out of a listbox, a number of people traveling, and where they wish to stay(ex. hotel, tent, etc.) after the user selects one for each category and hits the "add to invoice" button, the fields in the invoice should get filled with the corresponding information. Now my question is how can I write code that will insert information in the next row down after the previous row has been filled? basically what logic and programming structure do I need in my function that will know when the first row in the invoice is filled. I'm struggling at the part where when the "add to invoice" button is clicked. some data is added to the invoice, and if the user wants to book another trip, the second trip should be appended in the second row of the invoice. what is happening in mine is that whenever I book another trip, the first one gets overwritten when in fact it should be left intact and the data should get appended in the next row down.
Code: <html> <head> </head> <script type="text/javascript"> function addit() { var f = document.myform; var cost = 0; var percentage = 0; if(f.destination.selectedIndex == -1) { alert("please select a trip from the list"); return false; } if((f.travelers[0].checked == false) && (f.travelers[1].checked == false) && (f.travelers[2].checked == false) && (f.travelers[3].checked == false) && (f.travelers[4].checked == false) && (f.travelers[5].checked == false)) { alert("please specify the number of people traveling") return false; } if(f.accomodation.selectedIndex == -1) { alert("please specify your place of stay") return false; } switch(f.destination.selectedIndex) { case 0: document.myform.trip1.value="Mt. Kilimanjaro"; cost="2600"; break; case 1: document.myform.trip1.value="Denali"; cost="2000"; break; case 2: document.myform.trip1.value="Mt. Everest"; cost="3500"; break; case 3: document.myform.trip1.value="Maui"; cost="2700"; break; case 4: document.myform.trip1.value="Machu-Pichu"; cost="3100"; break; } for(i=0;i<f.travelers.length;i++) { if(f.travelers[i].checked) f.num1.value=f.travelers[i].value; } f.cost1.value=parseInt(f.num1.value) * parseInt(cost); switch(document.myform.accomodation.selectedIndex) { case 0: percentage="0.00"; break; case 1: percentage="0.05"; break; case 2: percentage="0.15"; break; case 3: percentage="0.22"; break; } f.accom1.value=f.cost1.value * parseFloat(percentage); f.total1.value=parseInt(f.cost1.value) + parseInt(f.accom1.value); } function deleteit() { var f = document.myform; var txtbox = document.getElementsByClassName("text"); var rad = document.getElementsByClassName("rad"); f.destination.selectedIndex=-1; f.accomodation.selectedIndex=-1; for(j=0;j<txtbox.length;j++) { txtbox[j].value=""; } for(x=0;x<rad.length;x++) { rad[x].checked=false; } } function submitform() { document.myform.submit(); } </script> <body> <form name="myform"> <table align="center" border="1" bgcolor="skyblue" cellpadding="0" cellspacing="0"> <tr><th>Trips Available</th><th>Number</br> Traveling</th><th>Accomodation</br> Type</th><th>Invoice</th></tr> <tr><td align="center"><select name="destination" id="Select1" size="4"> <option>Mt. Kilimanjaro</option> <option>Denali</option> <option>Mt. Everest</option> <option>Maui</option> <option>Machu-Pichu</option> </select></td> <td align="center">1<input type="radio" name="travelers" value="1" class="rad"></br>2<input type="radio" name="travelers" value="2" class="rad"/></br>3<input type="radio" name="travelers" value="3" class="rad"/></br>4<input type="radio" name="travelers" value="4" class="rad"/></br>5<input type="radio" name="travelers" value="5" class="rad"/></br>6<input type="radio" name="travelers" value="6" class="rad"/></td> <td align="center"> <select name="accomodation" id="Select2" size="3"> <option value=0>Tents</option> <option>Yurts</option> <option>Hostels</option> <option>Hotels</option> </select></td> <td><table width="90%" align="center" cellpadding="2"> <tr><th>Trip</th><th>Num</th><th>Base</br>cost</th><th>Accom.</br>Surcharge</th><th>Total</th></tr> <tr><td><input type="text" name="trip1" class="text" readonly></td><td><input type="text" name="num1" size="1" class="text" readonly></td><td><input type="text" name="cost1" class="text" readonly></td><td><input type="text" name="accom1" class="text" readonly></td><td><input type="text" name="total1" class="text" readonly></td></tr> <tr><td><input type="text" name="trip2" class="text" readonly></td><td><input type="text" name="num2" size="1" class="text" readonly></td><td><input type="text" name="cost2" class="text" readonly></td><td><input type="text" name="accom2" class="text" readonly></td><td><input type="text" name="total2" class="text" readonly></td></tr> <tr><td><input type="text" name="trip3" class="text" readonly></td><td><input type="text" name="num3" size="1" class="text" readonly></td><td><input type="text" name="cost3" class="text" readonly></td><td><input type="text" name="accom3" class="text" readonly></td><td><input type="text" name="total3" class="text" readonly></td></tr> <tr><td><input type="text" name="trip4" class="text" readonly></td><td><input type="text" name="num4" size="1" class="text" readonly></td><td><input type="text" name="cost4" class="text" readonly></td><td><input type="text" name="accom4" class="text" readonly></td><td><input type="text" name="total4" class="text" readonly></td></tr> </table></td></tr> </tr> <tr><td><input type="button" value="Add to Invoice" onclick="addit()"/></td><td><input type="button" value="Clear" onclick="deleteit()"/></td><td><input type="button" value="Buy Now" onclick="submitform()"/></td><td align="right">Total Sale:<input type="text" name="total" readonly/></td></tr> </table></form> </body> </html> Similar Tutorials<!-- ** Need help completing the javascript in this example ** --> Code: <html> <head> <title>Convert ListBox data into 4 Text Boxes</title> <script language="javascript"> function SplitText ( // NEED HELP WITH THIS CODE split text ","; convert to ['textbox1','textbox2','textbox3','textbox4'] } </script> </head> <body> <form name="convert"> <p style="margin: 2px"> <h3>Convert selected data to textboxes</h3> <!-- SELECT DATA FROM LIST BOX --> <select size="1" name="ListBox" onChange="SplitText();"> <option value="jim,bob,rick,paul" >==Row1==</option> <option value="pete,jack,chris,craig">==Row2==</option> <option value="mary,jane,lisa,kim" >==Row3==</option> </select> </p> <h3>In this example say we selected row1</h3> <!-- THE SELECTED DATA GETS SPLIT AND INSERTED INTO THESE 4 TEXTBOXES --> <p style="margin: 2px"> <input type="text" name="textbox1" value="jim"><br> <input type="text" name="textbox2" value="bob"><br> <input type="text" name="textbox3" value="rick"><br> <input type="text" name="textbox4" value="paul"><br> </p> </form> </body> </html> <!-- ** Need help completing the javascript in this example ** --> <html> <head> <title>Convert ListBox data into 4 Text Boxes</title> <script language="javascript"> function SplitText ( // NEED HELP WITH THIS CODE split text ","; convert to ['textbox1','textbox2','textbox3','textbox4'] } </script> </head> <body> <form name="convert"> <p style="margin: 2px"> <h3>Convert selected data to textboxes</h3> <!-- SELECT DATA FROM LIST BOX --> <select size="1" name="ListBox" onChange="SplitText();"> <option value="jim,bob,rick,paul" >==Row1==</option> <option value="pete,jack,chris,craig">==Row2==</option> <option value="mary,jane,lisa,kim" >==Row3==</option> </select> </p> <h3>In this example say we selected row1</h3> <!-- THE SELECTED DATA GETS SPLIT AND INSERTED INTO THESE 4 TEXTBOXES --> <p style="margin: 2px"> <input type="text" name="textbox1" value="jim"><br> <input type="text" name="textbox2" value="bob"><br> <input type="text" name="textbox3" value="rick"><br> <input type="text" name="textbox4" value="paul"><br> </p> </form> </body> </html> I am creating a recipe cookbook program. On the main page, I have a top frame (named "nav") and bottom frame (named "recipe_layout"). There is a listbox in the BOTTOM frame containing the recipe names, and a "View Recipe" button in the TOP frame. The user would select a recipe and then click the button to view the recipe in the bottom frame. I believe that I need to insert the code to make this work with the button (?), and I think my problem is that I'm not accessing the bottom frame correctly: CURRENT CODE FOR LISTBOX IN BOTTOM FRAME <form name="recipe_form" style="margin-top:30"> <select name="name_dropdown" multiple size="2"> <option selected="selected">Search byName</option> <option value="applepie.html">Apple Pie</option> CURRENT CODE FOR BUTTON IN TOP FRAME <input type="button" value="View Recipe" onclick="parent.recipe_layout.location.href='recipe_form.name_dropdown.options[selectedIndex].value'"> Thank you so much in advance!! Hello, I have an entry form using multiple select boxes as data entry in the upper portion of my page. below i want additional details of the item selected in a table like textboxes by clicking an add button.So whenever i click the add button a new row of text boxes is again created. problem: upon selecting an additional/new item from the select boxes the first row of textboxes doesn't retain it's value it reflects the currently selected values. all the data mentioned above is contained in a single page is it possible? using a classic asp using javascript to do this?please help, i'm really lost..attach is a snopshot of my page... Hi and thanks for your help, I have two text boxes on my page and a third where I would like it to automatically subtract the two any time either one of them is changed. What is the simplest way to do this? Thanks again for your help, Will Hello! coding forums gals, I am resorting to you for help with a html form that uses javascript to validate data. the form is an invoice for a trip order where the user can select a trip location out of a listbox, a number of people traveling, and where they wish to stay(ex. hotel, tent, etc.) after the user selects one for each category and hits the "add to invoice" button, the fields in the invoice should get filled with the corresponding information. Now my question is how can I write code that will insert information in the next line down and all other lines below if the user wants to schedule more than one trip at a time? basically what logic and programming structure do I need in my function that will know when the first line in the invoice is filled and will add data in the next line down. after I have successfully placed an order, and I want to make another one, how do I get javascript to output data on the second line? Code: <html> <head> </head> <script type="text/javascript"> function addit() { var f = document.myform; var cost = 0; var percentage = 0; switch(f.destination.selectedIndex) { case 0: document.myform.trip1.value="Mt. Kilimanjaro"; cost="2600"; break; case 1: document.myform.trip1.value="Denali"; cost="2000"; break; case 2: document.myform.trip1.value="Mt. Everest"; cost="3500"; break; case 3: document.myform.trip1.value="Maui"; cost="2700"; break; case 4: document.myform.trip1.value="Machu-Pichu"; cost="3100"; break; } for(i=0;i<f.travelers.length;i++) { if(f.travelers[i].checked) f.num1.value=f.travelers[i].value; } f.cost1.value=parseInt(f.num1.value) * parseInt(cost); switch(document.myform.accomodation.selectedIndex) { case 0: percentage="0.00"; break; case 1: percentage="0.05"; break; case 2: percentage="0.15"; break; case 3: percentage="0.22"; break; } f.accom1.value=f.cost1.value * parseFloat(percentage); f.total1.value=parseInt(f.cost1.value) + parseInt(f.accom1.value); } </script> <body> <form name="myform"> <table align="center" border="1" bgcolor="skyblue" cellpadding="0" cellspacing="0"> <tr><th>Trips Available</th><th>Number</br> Traveling</th><th>Accomodation</br> Type</th><th>Invoice</th></tr> <tr><td align="center"><select name="destination" id="Select1" size="4"> <option>Mt. Kilimanjaro</option> <option>Denali</option> <option>Mt. Everest</option> <option>Maui</option> <option>Machu-Pichu</option> </select></td> <td align="center">1<input type="radio" name="travelers" value="1"></br>2<input type="radio" name="travelers" value="2"/></br>3<input type="radio" name="travelers" value="3"/></br>4<input type="radio" name="travelers" value="4"/></br>5<input type="radio" name="travelers" value="5"/></br>6<input type="radio" name="travelers" value="6"/></td> <td align="center"> <select name="accomodation" id="Select2" size="3"> <option value=0>Tents</option> <option>Yurts</option> <option>Hostels</option> <option>Hotels</option> </select></td> <td><table width="90%" align="center" cellpadding="2"> <tr><th>Trip</th><th>Num</th><th>Base</br>cost</th><th>Accom.</br>Surcharge</th><th>Total</th></tr> <tr><td><input type="text" name="trip1" readonly></td><td><input type="text" name="num1" size="1" readonly></td><td><input type="text" name="cost1" readonly></td><td><input type="text" name="accom1" readonly></td><td><input type="text" name="total1" readonly></td></tr> <tr><td><input type="text" name="trip2" readonly></td><td><input type="text" name="num2" size="1" readonly></td><td><input type="text" name="cost2" readonly></td><td><input type="text" name="accom2" readonly></td><td><input type="text" name="total2" readonly></td></tr> <tr><td><input type="text" name="trip3" readonly></td><td><input type="text" name="num3" size="1" readonly></td><td><input type="text" name="cost3" readonly></td><td><input type="text" name="accom3" readonly></td><td><input type="text" name="total3" readonly></td></tr> <tr><td><input type="text" name="trip4" readonly></td><td><input type="text" name="num4" size="1" readonly></td><td><input type="text" name="cost4" readonly></td><td><input type="text" name="accom4" readonly></td><td><input type="text" name="total4" readonly></td></tr> </table></td></tr> </tr> <tr><td><input type="button" value="Add to Invoice" onclick="addit()"/></td><td><input type="button" value="Clear"/></td><td><input type="button" value="Buy Now"/></td><td align="right">Total Sale:<input type="text" name="total" readonly/></td></tr> </table></form> </body> </html> I have the following code below to make and populate a select box for a row. It is working on my IE, Firefox, and Chrome, but some others are having problems. It makes the select box, but it does not put the options in there. I am having issues troubleshooting because I cannot replicate the error. Any ideas? Code: newManufacturerCell = newRow.appendChild(document.createElement('td')); var newSelect=newManufacturerCell.appendChild(document.createElement('select')); var firstOption=document.createElement('option'); var secondOption=document.createElement('option'); firstOption.text="Dell DCS"; secondOption.text="Hp"; newSelect.add(firstOption,null); newSelect.add(secondOption,null); newSelect.id="man"+count; I currently have two selectbox, the first for categories and the second for subcategories. When an option from the category selectbox is chosen I would like the subcategory selectbox to be filled with options drawn from an array. The following code I have works for Chrome and Firefox but not in IE, I would appreciate any help to fix the code or new code which does a similar function. HTML: Code: <select size="9" id="category" name="category" onclick="return categoryChange();"> <option>Antiques ></option> <option>Art and Crafts ></option> </select> <select style="visibility:hidden" id="subcategory" name="subcategory" size="9"> </select> JAVASCRIPT: Code: function addOption(selectbox,text,value){ var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } var antiques = new Array("Furniture","Ceramics","Glass"); var art = new Array("Drawings and Paintings","Photographs"); function categoryChange(){ document.getElementById("subcategory").style.visibility = "visible"; document.getElementById("subcategory").innerHTML = ""; if(document.getElementById("category").value == "Antiques >"){ for (var i=0; i < antiques.length;++i){ addOption(document.myForm.subcategory, antiques[i], antiques[i]); } } else if(document.getElementById("category").value == "Art and Crafts >"){ for (var i=0; i < art.length;++i){ addOption(document.myForm.subcategory, art[i], art[i]); } } } Hi All, I have a javascript function which adds a label and value to a select widget in its parent window. The function is working fine in firefox and chrome without any errors or warnings. But it is not working in internet explorer. Please tell me what the issue is. Thanks in advance for your help. Code: function addToParent( formName, selectName, name, label ) { var parent = window.opener; var selectWidget = parent.document.forms[formName].elements[selectName]; if( selectWidget ) { var length = selectWidget.length; selectWidget[length] = new Option( name, label, false, false ); } } When I tried to debug, internet explorer shows an error in the following line Code: selectWidget[length] = new Option( name, label, false, false ); Is there anything wrong with this statement ?? Okay so I'm trying to come up with as many alternative methods to accomplish something. So I'm just seeking input from anyone who is willing to supply some. After the user clicks on a match type it'll know HOW MANY sides to the match there are so say for a singles match it'd have 2 sides (1 vs. 1) for a Triple Threat Match it'd have 3 sides (1 vs. 1 vs. 1) and so on. All matches have a stored field in the database of how many sides they have. So I'm thinking that I could have it create 3 divs (or something) down in the competitors area of how many sides there are in the match (separated by a VS. text block) and when the user selects a character from the dropdown and adds a character the user can maybe drag and drop the character's name to whatever side they choose. Its one idea. If you think of an EASIER more EFFICIENT way to do something like this and have an idea say something please or even if you can't let me know that you think it's a worth while idea. Code: <label for="matchtypedrop<?php echo $i+1 ?>">Match Type:</label> <select class="dropdown" name="matchtypedrop<?php echo $i+1 ?>" id="matchtypedrop<?php echo $i+1 ?>" title="Match Type <?php echo $i+1 ?>"> <option value="0">- Select -</option> <?php $query = 'SELECT id, matchtype FROM matchtypes'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['matchtype']."</option>\r"; } ?> </select> <label for="competitors<?php echo $i+1 ?>">Competitors:</label><ul id="competitors<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul> <select class="dropdown" name="charactersdrop<?php echo $i+1 ?>" id="charactersdrop<?php echo $i+1 ?>" title="Characters Dropdown <?php echo $i+1 ?>" style="margin-left: 195px;"> <option value="0">- Select -</option> <?php $query = 'SELECT id, `character` FROM characters ORDER BY `character`'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['character']."</option>\r"; } ?> </select> <input type="button" value="Add Character" class="" onclick="Competitors(<?php echo $i+1 ?>)"/> Hi all! I'm using a multiselect box on my website, similar to this one: <Select Name="multiselect[]" multiple="multiple"> <option>This is option 1</option> <option>This is option 2</option> <option>This is option 3</option> <option>This is option 4</option> </select> Now I want to set option 1, option 2 and option 3 as selected (highlighted) in javascript. How would I go about doing this? I tried something like this: document.taakform.elements['multiselect[]'].selectedIndex = "1" document.taakform.elements['multiselect[]'].selectedIndex = "2" document.taakform.elements['multiselect[]'].selectedIndex = "3" Of course this doesn't work (else I wouldn't be posting here ), but I hope you catch my drift. Thanks in advance guys (and gals)! Hi All Not sure if this is the right place to post but could do with some help. Scenario: 1 Box holds 3 items, Complete box weighs 75g, each item 25g, customer chooses their own 3 combo items. This could be the same all the same item or 3 different items. I need a script that will require the selections to make up 75g in order to continue the process. i.e customer can only continue when 3 items / 75g worth are selected. Here is a short version, I have about 12 selectors at the moment and possible more will be created (if that matters). Code: <form name="cart_quantity" action="myProduct?action=add_product" method="post" enctype="multipart/form-data"> < <div class="placeholder"> <img src="" alt="Image Placeholder" /> </div> <label class="attribsSelect" for="attrib-6">Hard Boiled 1</label><br /> <select name="id[6]" id="attrib-6"> <option value="">Select Portion</option> <option value="24">25g</option> <option value="25">50g</option> <option value="26">75g</option> </select> <div class="placeholder"> <img src="" alt="Image Placeholder" /> </div> <label class="attribsSelect" for="attrib-7">Hard Boiled 2</label><br /> <select name="id[7]" id="attrib-7"> <option value="">Select Portion</option> <option value="27">25g</option> <option value="28">50g</option> <option value="29">75g</option> </select> <div class="placeholder"> <img src="" alt="Image Placeholder" /> </div> <label class="attribsSelect" for="attrib-8">Hard Boiled 3</label><br /> <select name="id[8]" id="attrib-8"> <option value="">Select Portion</option> <option value="30">25g</option> <option value="31">50g</option> <option value="32">75g</option> </select> <div class="placeholder"> <img src="" alt="Image Placeholder" /> </div> <label class="attribsSelect" for="attrib-9">Hard Boiled 4</label><br /> <select name="id[9]" id="attrib-9"> <option value="">Select Portion</option> <option value="33">25g</option> <option value="34">50g</option> <option value="35">75g</option> </select> </form> The section of the form is just the portion with selctors, there are other fields with radio buttons for color choice etc. I have searched for something like this all over but cant find it. Please please please could some genius out there help. Thanks in advance Hello, I just joined the forum. I'm hoping someone could help me out or point me in the right direction. I am trying to set up a simple interaction for users. The user would be required to select a width then height from two separate drop down menus. I used this as an example to work from: http://www.w3.org/TR/WCAG20-TECHS/wo...dynselect.html The list of heights would not be available until the user selects a width.(similar to the example link above). Each width would have slightly different heights associated with it. After the user selects a width then height an image would be displayed based on that combination. So for example if the user selects 12w/30h they would see "01.jpg" if the user selects 12w/36h they would see "02.jpg". This would all be done on the same page. The user should be able to update the image by combining the different width/height options indefinitely. If anyone has a link to an example or can provide a basic structure I could build of off I would be extremely grateful, thanks. I'm still very new to Javascript, like really new. I'm trying to use this sliding menu script, and I want to have multiple menus on the same page. Problem is, I can't get multiple ID's for the menus to work, so if I click one menu's slider button, then it will always only affect the first menu, regardless of which I click. Here's where I think I need to modify the code, at the top: Code: <script type="text/javascript"> var sliderIntervalId = 0; var sliderHeight = 232; var sliding = false; var slideSpeed = 10; function Slide() And where the ID value is defined: Code: function SlideUpRun() { slider = document.getElementById('exampleSlider'), slider = document.getElementById('slider2'); if(sliderHeight <= 0) { sliding = false; sliderHeight = 0; slider.style.height = '0px'; clearInterval(sliderIntervalId); Obviously, these are just snippets of the whole code, I didn't know if less/more is needed to be shwon. Can anyone help on this? I just need to know how to separate it, so I can add multiple menus to the same page. Hi, I am trying to add markers to Google Maps, they are working fine but some of the markers are of same location, thus Google Map will show only one marker for them. Is it possible to show all markers no matter if they are of same location. Help is much appreciated. Thanks I am working with the quiz found below (Multiple Choice Quiz that is instantly graded/checked), and would like to add pictures to the questions and rollover sound effects. I have figured how to add the picture, but not the sound. Sound effects are played when added to the html section, but not when added to the javascript coding. I am alright with html and css, but not with javascript. Any help from the javascript experts would be appreciated. ********* Coding Example ********* <HTML> <HEAD> <TITLE>The JavaScript Source: Miscellaneous : Multiple Choice Quiz</TITLE> <META HTTP-EQUIV="The JavaScript Source" CONTENT = "no-cache"> <META NAME="description" CONTENT="Add a quiz to your Web page without using a server-side script. Easy to set-up. Questions and answers are stored in a multi-dimensional array format in an external file. The quiz is marked in real time, and once answered, questions are set to read-only. A summary of the users score is alerted at the end."> <META NAME="date" CONTENT="2005-12-27"> <META NAME="channel" CONTENT="Developer"> <META NAME="author" CONTENT="James Crooke"> <META NAME="section" CONTENT="Miscellaneous"> <style type="text/css"> <!-- .question { color:darkblue; font-size:14px; font-weight:bold; } --> </style> <script type="text/javascript"> <!-- /* This script and many more are available free online at The JavaScript Source :: http://javascript.internet.com Created by: James Crooke :: http://www.cj-design.com */ var useranswers = new Array(); var answered = 0; function renderQuiz() { for(i=0;i<questions.length;i++) { document.writeln('<p class="question">' + questions[i] + ' <span id="result_' + i + '"><img src="blank.gif" style="border:0" alt="" /></span></p>'); for(j=0;j<choices[i].length;j++) { document.writeln('<input type="radio" name="answer_' + i + '" value="' + choices[i][j] + '" id="answer_' + i + '_' + j + '" class="question_' + i + '" onclick="submitAnswer(' + i + ', this, \'question_' + i + '\', \'label_' + i + '_' + j + '\')" /><label id="label_' + i + '_' + j + '" for="answer_' + i + '_' + j + '"> ' + choices[i][j] + '</label><br />'); } } document.writeln('<p><input type="submit" value="Show Score" onclick="showScore()" /> <input type="submit" value="Reset Quiz" onclick="resetQuiz(true)" /></p><p style="display:none"><img src="correct.gif" style="border:0" alt="Correct!" /><img src="incorrect.gif" style="border:0" alt="Incorrect!" /></p>'); } function resetQuiz(showConfirm) { if(showConfirm) if(!confirm("Are you sure you want to reset your answers and start from the beginning?")) return false; document.location = document.location; } function submitAnswer(questionId, obj, classId, labelId) { useranswers[questionId] = obj.value; document.getElementById(labelId).style.color = "grey"; //disableQuestion(classId); showResult(questionId); answered++; } function showResult(questionId) { if(answers[questionId] == useranswers[questionId]) { document.getElementById('result_' + questionId).innerHTML = '<img src="correct.gif" style="border:0" alt="Correct!" />'; // I tried to make the background a different colour for the answer document.getElementById(questionId).style.border ='1px'; } else { document.getElementById('result_' + questionId).innerHTML = '<img src="incorrect.gif" style="border:0" alt="Incorrect!" />'; } } function showScore() { if(answered != answers.length) { alert("You have not answered all of the questions yet!"); return false; } questionCount = answers.length; correct = 0; incorrect = 0; for(i=0;i<questionCount;i++) { if(useranswers[i] == answers[i]) correct++; else incorrect++; } pc = Math.round((correct / questionCount) * 100); alertMsg = "You scored " + correct + " out of " + questionCount + "\n\n"; alertMsg += "You correctly answered " + pc + "% of the questions! \n\n"; if(pc == 100) alertMsg += response[0]; else if(pc >= 90) alertMsg += response[1]; else if(pc >= 70) alertMsg += response[2]; else if(pc > 50) alertMsg += response[3]; else if(pc >= 40) alertMsg += response[4]; else if(pc >= 20) alertMsg += response[5]; else if(pc >= 10) alertMsg += response[6]; else alertMsg += response[7]; if(pc < 100) { if(confirm(alertMsg)) resetQuiz(false); else return false; } else { alert(alertMsg); } } function disableQuestion(classId) { var alltags=document.all? document.all : document.getElementsByTagName("*") for (i=0; i<alltags.length; i++) { if (alltags[i].className == classId) { alltags[i].disabled = true; } } } var questions = new Array(); var choices = new Array(); var answers = new Array(); var response = new Array(); // To add more questions, just follow the format below. questions[0] = "1) JavaScript is ..." ; choices[0] = new Array(); choices[0][0] = "the same as Java"; choices[0][1] = "kind of like Java"; choices[0][2] = "different than Java"; choices[0][3] = "ther written part of Java"; answers[0] = choices[0][2]; ///////// THIS IS THE SECTION THAT I'M TRYING TO WORK ON ///////// // image works, but sound doesn't // questions[1] = "<a href='javascriptHTMLSound' id='dummyspan' // the smiley is actually a colon followed by a D as in "DHTML" onMouseOver='DHTMLSound('success.wav')'><img src='some_image.gif'></a>"; choices[1] = new Array(); choices[1][0] = "Play This" + "<a href='javascriptlaySound('success.wav')'>Play This</a>"; choices[1][1] = "objective"; choices[1][2] = "evil"; choices[1][3] = "object based"; answers[1] = choices[1][3]; ///////////////////////////////////////////////////////////////// questions[2] = "3) To comment out a line in JavaScript ..."; choices[2] = new Array(); choices[2][0] = "Precede it with two forward slashes, i.e. '//'"; choices[2][1] = "Precede it with an asterisk and a forward slash, i.e. '*/'"; choices[2][2] = "Precede it with an asterisk, i.e. '*'"; choices[2][3] = "Precede it with a forward slash and an asterisk, i.e. '/*'"; answers[2] = choices[2][0]; questions[3] = "4) JavaScript can only run on Windows"; choices[3] = new Array(); choices[3][0] = "True"; choices[3][1] = "False"; answers[3] = choices[3][1]; questions[4] = "5) Semicolons are optional at the end of a JavaScript statement."; choices[4] = new Array(); choices[4][0] = "True"; choices[4][1] = "False"; answers[4] = choices[4][0]; questions[5] = "strings are..."; choices[5] = new Array(); choices[5][0] = "strings, numbers, BooBoos, and nulls"; choices[5][1] = "strings, text, Booleans, and nulls"; choices[5][2] = "strings, numbers, Booleans, and nulls"; choices[5][3] = "strings, numbers, Booleans, and zeros"; answers[5] = choices[5][2]; // response for getting 100% response[0] = "Excellent, top marks!"; // response for getting 90% or more response[1] = "Excellent, try again to get 100%!" // response for getting 70% or more response[2] = "Well done, that is a good score, can you do better?"; // response for getting over 50% response[3] = "Nice one, you got more than half of the questions right, can you do better?"; // response for getting 40% or more response[4] = "You got some questions right, you can do better!"; // response for getting 20% or more response[5] = "You didn't do too well, why not try again!?"; // response for getting 10% or more response[6] = "That was pretty poor! Try again to improve!"; // response for getting 9% or less response[7] = "Oh dear, I think you need to go back to school (or try again)!"; //--> </script> </HEAD> <BODY BGCOLOR=#ffffff vlink=#0000ff > <script> function DHTMLSound(surl) { document.getElementById("dummyspan").innerHTML="<embed src='"+surl+"' hidden=true autostart=true loop=false>"; } </script> <script type="text/javascript"> <!-- renderQuiz(); //--> </script> </body></html> ********* I have also tried the following sound ideas, but none work "within" the javascript -- they do work when assigned to a button inside the html however... The trick is, I want to be able to display an image within the question, then mouseover a <span> of text or an image (preferrably NOT a link <a>) and have the sounds played as part of the choices for the question. For a slightly different purpose, I'm also interested in being able to have the correst answer (for more complicated quizes) appear beside the question, in a <div> if possible, rather than an alert, to give the solution / reasoning for the correct answer. Any help at all would be really appreciated. Okay, I'm having some trouble getting my head around how to do this.. Code: <select> <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> </select> <select> <option value="Rhino">Rhino</option> <option value="Bird">Bird</option> <option value="Rooster">Rooster</option> </select> <select> <option value="0202A">Rhino - Text</option> <option value="0203A">Rhino - Text2</option> <option value="0204A">Bird - Text1</option> <option value="0205A">Bird - Text2</option> <option value="0202B">Rhino - Text</option> <option value="0204B">Rhino - Text2</option> <option value="0204C">Rooster - Text1</option> <option value="0205C">Rooster - Text2</option> <option value="0206C">Rooster - Text3</option> </select> So say we had those three drop-downs. I'm looking to make it so that second drop-down only has options corresponding to a relationship between the first and the third drop-down. Example - if you select A in the first drop-down you only see Rhino and Bird in the second drop-down. If you select B you will only see Rhino in the second drop-down. Lastly, if you select C you will only see Rooster in the second drop-down. Just can't figure this out. >.< Hello, I need your help, I can seem to get this to work. I want to be able to use an IIF to check if a textbox empty ie. IIF(textbox1 = "" || textbox = null, "it is empty","it is not empty") This doesnt seem to be working. Any ideas? - Clueless =? Hi there...I have an autosuggest that I got from a friend. My question is ... the autosuggest works well on my business textbox - what would the code look like to get it to work on the region textbox (or how do I get it to work on more than one textbox - can I just make a copy of the js file and change stuff)... Here is the html code for the index.html page with two boxes and a submit button... 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>Welcome</title> <link href="searchfield.css" rel="stylesheet" type="text/css" media="screen" /> <script type="text/javascript" src="searchfield1.js"></script> </head> <body> <form name="searchresults" action="Site/searchresults2.php" method="post" > <input name="Business" class="textfield_effect" type="text" value="Enter Business Type or Name" size="30" onfocus="if(this.value==this.defaultValue) this.value='';" autocomplete="off" id="businessquery" /> <input name="Region" class="textfield_effect" type="text" value="Enter Suburb or Postcode" size="30" onfocus="if(this.value==this.defaultValue) this.value='';" autocomplete="off" id="regionquery" /> <input type="submit" class="textfield_button" value="Search"/> </body> </html> and here is the code for the file called searchfield1.js that powers the autosuggest... Code: this.searchfield = function(){ // CONFIG # // this is id of the search field you want to add this script to. // You can use your own id just make sure that it matches the search field in your html file. var id = "businessquery"; // Text you want to set as a default value of your search field. var defaultText = "Enter Business Type or Name!"; // set to either true or false // when set to true it will generate search suggestions list for search field based on content of variable below var suggestion = true; // static list of suggestion options, separated by comma // replace with your own var suggestionText = "Accounting Firm, Independent Actors, Administration of Public Programs, above the fold, absolute link, accessibility, address bar, affordance, alt text, alt tag, anchor, animated GIF, anti-alias, applet, assumed knowledge, authoring, automagically, autoresponder, back end/front end, backup, bandwidth, banner ad, banner blindness, belt-and-suspenders, bitmap, blog, blogger, blogging, bookmark, breadcrumb, broadband, browser, cache, cached files, call to action, Cascading Style Sheets , chatroom, chrome, click-through rate, client-side/server-side, closure, compatibility mode, data compression, content management system , contextual menu, convergence, cookie, cost-per-clickthrough, cost-per-thousand, crawler, cross-browser compatibility, cybersquatter, deep-linking, default, degrade gracefully, deprecated, design pattern, directory, disjointed rollover, dither, div, div-i-tis, divitis, document type declaration, doctype, document type definition, Domain Name System, DNS server, domain name, DomaiNZ, doorway/gateway page, dots-per-inch, download, Dublin Core metadata, dynamic HTML, e-commerce, email, element, encryption, favicon.ico, File Transfer Protocol, FTP client, firewall, Fireworks, Flash, Flash Generator, flow chart, fold, above-the-fold, footer navigation, form, folksonomy, frame, frameset, front end/back end, gateway page, global navigation, granularity, Graphic Interchange Format, Graphical User Interface, hack, handle, haptics, hexadecimal colours, hits, host, hosting, hotspot, HyperText Markup Language, HyperText Transfer Protocol, HTML markup, HTML-text, hyperlink, iframes, i-mode, image map, impression, include, information architecture, information foraging, initialism, integration, interactive television, interface, internet, interstitial, intranet, Initial Public Offering, Internet Protocol, IP address, IP number, Internet Service Provider, JavaScript, Joint Photographers Expert Group, label, landing page, legacy content, link: absolute, relative, root, link farm, link rot, definition, ordered, unordered, listserv, logfiles, logfile analysis, look-and-feel, lossless compression, lossy compression, macron, mailing lists, markup, meta element, metadata, meta tag, mine-sweeping, MP3, MySQL, natural language, navigation, open source, optimise, optimisation, opt-in/opt-out, PageRank (PR), parasite economy, design pattern, perceived affordance, permission-based marketing, phishing, PHP: Hypertext Preprocessor, Portable Document Format, web portal, Pretty Good Privacy, pixel, plug-in, pop-up window, pop-under, Portable Network Graphic, prosumer, QuickTime, quirks mode, reciprocal links, referrer, referrer log, Really Simple Syndication, relative link, Realtime Transport Protocol, robot, robots file, robots.txt, rollover, disjointed rollover, root, root directory, root link, scan, scanning, schematic, SCM, SCP, search engine, search engine marketing, search engine optimisation, Section 508, Secure Sockets Certificate, semantic markup, server, sever-side/client-side, server-side include, session, session tracking, Shockwave, shopping-cart, shortcut icon, Simple Object Access Protocol, site feed, sitemap, smart tags, Synchronised Multimedia Integration Language, sniffer, spam, spim, spider, splash page, splash screen, spyware, standardista, standards-compliant/strict mode, status bar, sticky, streaming, streaming media, structured query language, stylesheet, system font, tags, tags/tagging, target, template, top-level navigation, topic path, traffic, transform gracefully, transparent GIF, trackback, typosquatter, Unicode, Unicode Transformation Format, Unified Modeling Language, Uniform Resource Identifier, Uniform Resource Locator, uploading, usability, user session, code standards, form input, vector, vector-based file, version control, viral marketing, virus, visual editor, web, Web 2.0, web accessibility, web-authoring, web browser, web font, typeface, web-log, web server logs, websafe colours, palette, web standards, WebTV, what-you-see-is-what-you-get, wireframe, Wireless Application Protocol, Wireless Markup Language, Worldwide Web, eXtensible Markup Language, XML schema"; // END CONFIG (do not edit below this line, well unless you really, really want to change something :) ) // Peace, // Alen var field = document.getElementById(id); var classInactive = "sf_inactive"; var classActive = "sf_active"; var classText = "sf_text"; var classSuggestion = "sf_suggestion"; this.safari = ((parseInt(navigator.productSub)>=20020000)&&(navigator.vendor.indexOf("Apple Computer")!=-1)); if(field && !safari){ field.value = defaultText; field.c = field.className; field.className = field.c + " " + classInactive; field.onfocus = function(){ this.className = this.c + " " + classActive; this.value = (this.value == "" || this.value == defaultText) ? "" : this.value; }; field.onblur = function(){ this.className = (this.value != "" && this.value != defaultText) ? this.c + " " + classText : this.c + " " + classInactive; this.value = (this.value != "" && this.value != defaultText) ? this.value : defaultText; clearList(); }; if (suggestion){ var selectedIndex = 0; field.setAttribute("autocomplete", "off"); var div = document.createElement("div"); var list = document.createElement("ul"); list.style.display = "none"; div.className = classSuggestion; list.style.width = field.offsetWidth + "px"; div.appendChild(list); field.parentNode.appendChild(div); field.onkeypress = function(e){ var key = getKeyCode(e); if(key == 13){ // enter selectList(); selectedIndex = 0; return false; }; }; field.onkeyup = function(e){ var key = getKeyCode(e); switch(key){ case 13: return false; break; case 27: // esc field.value = ""; selectedIndex = 0; clearList(); break; case 38: // up navList("up"); break; case 40: // down navList("down"); break; default: startList(); break; }; }; this.startList = function(){ var arr = getListItems(field.value); if(field.value.length > 0){ createList(arr); } else { clearList(); }; }; this.getListItems = function(value){ var arr = new Array(); var src = suggestionText; var src = src.replace(/, /g, ","); var arrSrc = src.split(","); for(i=0;i<arrSrc.length;i++){ if(arrSrc[i].indexOf(value.toLowerCase()) >= 0){ arr.push(arrSrc[i]); }; }; return arr; }; this.createList = function(arr){ resetList(); if(arr.length > 0) { for(i=0;i<arr.length;i++){ li = document.createElement("li"); a = document.createElement("a"); a.href = "javascript:void(0);"; a.i = i+1; a.innerHTML = arr[i]; li.i = i+1; li.onmouseover = function(){ navListItem(this.i); }; a.onmousedown = function(){ selectedIndex = this.i; selectList(this.i); return false; }; li.appendChild(a); list.setAttribute("tabindex", "-1"); list.appendChild(li); }; list.style.display = "block"; } else { clearList(); }; }; this.resetList = function(){ var li = list.getElementsByTagName("li"); var len = li.length; for(var i=0;i<len;i++){ list.removeChild(li[0]); }; }; this.navList = function(dir){ selectedIndex += (dir == "down") ? 1 : -1; li = list.getElementsByTagName("li"); if (selectedIndex < 1) selectedIndex = li.length; if (selectedIndex > li.length) selectedIndex = 1; navListItem(selectedIndex); }; this.navListItem = function(index){ selectedIndex = index; li = list.getElementsByTagName("li"); for(var i=0;i<li.length;i++){ li[i].className = (i==(selectedIndex-1)) ? "selected" : ""; }; }; this.selectList = function(){ li = list.getElementsByTagName("li"); a = li[selectedIndex-1].getElementsByTagName("a")[0]; field.value = a.innerHTML; clearList(); }; }; }; this.clearList = function(){ if(list){ list.style.display = "none"; selectedIndex = 0; }; }; this.getKeyCode = function(e){ var code; if (!e) var e = window.event; if (e.keyCode) code = e.keyCode; return code; }; }; // script initiates on page load. this.addEvent = function(obj,type,fn){ if(obj.attachEvent){ obj['e'+type+fn] = fn; obj[type+fn] = function(){obj['e'+type+fn](window.event );} obj.attachEvent('on'+type, obj[type+fn]); } else { obj.addEventListener(type,fn,false); }; }; addEvent(window,"load",searchfield); And here is the code for the CSS file called searchfield.css Code: /* default (inactive field) */ .sf_inactive{ border:thin solid #CCCCCC; background:#ffffff; color:#666666; font-style: 0; } /* on focus (when field is clicked on) */ .sf_active{ border:2px solid #CCCCCC; background:#fff; color:#666666; } /* with text (when field is inactive but contains user's input) */ .sf_text{ border:2px solid #CCCCCC; background:#fff; color:#888; } /* suggestions box */ /* js code generates unordered list */ .sf_suggestion{ position:relative; } .sf_suggestion ul{ position:absolute; margin:0; padding:0; top:0; left:0; background-color: #FFFFFF; } .sf_suggestion li{ margin:0; padding:0; list-style:none; } .sf_suggestion li a{ display:block; text-indent:5px; color:#666666; } .sf_suggestion li.selected a{ color: #FFFFFF; background-color: #666666; } Many thanks for hints, suggestions and contributions |