JavaScript - Autosuggest For Two Textboxes
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 Similar TutorialsI want to have a simple code such that some data is stored in array. When we create a search box it has to give suggestions from the data stored in array. Hi All, i have an autosuggest function which i am trying to make the textbox value to change to the represent the value of the highlighted auto suggestion. i am trying to do this so that when i submit the form the correct value is passed to the next page where as at the moment only the text which is typed in the textbox is passed. here is my index.php PHP Code: <?php include("config.php");?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> Ajax Auto Suggest </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <link href="css/style.css" rel="stylesheet" type="text/css"> <!--[if gte IE 6]> <link rel="stylesheet" type="text/css" href="i_hate_IE.css" /> <![endif]--> <SCRIPT LANGUAGE="JavaScript" src="js/jquery.js"></SCRIPT> <SCRIPT LANGUAGE="JavaScript" src="js/script.js"></SCRIPT> <script type="text/javascript"> window.onload = function() { document.getElementById('keyword').setAttribute('autocomplete','off'); } </script> </HEAD> <BODY> <center> <div class="main"> <form id="test" name="form1" method="post" action="search.php"> <input type="hidden" name="mode" id="mode" value="1"/> <div id="holder"> <input type="text" name="keyword" id="keyword" tabindex="0"><img src="images/loading.gif" id="loading"> </div> <div id="ajax_response"></div> </form> </div> </center> </BODY> </HTML> here is my search.php PHP Code: <?php include("config.php"); $keyword = $_POST['keyword']; $sql = "select storeName,storeLink from ".$db_table." where ".$db_column." like '".$keyword."%' limit 0,1"; $result = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($result)) { #echo '<ul class="list">'; while($row = mysql_fetch_array($result)) { $link = $row['storeLink']; header('Location: '.$link.''); } } ?> and here is my script.js file Code: $(document).ready(function(){ $(document).click(function(){ $("#ajax_response").fadeOut('slow'); }); $("#keyword").focus(); var offset = $("#keyword").offset(); var width = $("#keyword").width()-2; $("#ajax_response").css("left",offset.left); $("#ajax_response").css("width",width); $("#keyword").keyup(function(event){ //alert(event.keyCode); var keyword = $("#keyword").val(); if(keyword.length) { if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13) { $("#loading").css("visibility","visible"); $.ajax({ type: "POST", url: "ajax_server.php", data: "data="+keyword, success: function(msg){ if(msg != 0) $("#ajax_response").fadeIn("slow").html(msg); else { $("#ajax_response").fadeIn("slow"); $("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>'); } $("#loading").css("visibility","hidden"); } }); } else { switch (event.keyCode) { case 40: { found = 0; $("li").each(function(){ if($(this).attr("class") == "selected") found = 1; }); if(found == 1) { var sel = $("li[class='selected']"); sel.next().addClass("selected"); sel.removeClass("selected"); } else $("li:first").addClass("selected"); } break; case 38: { found = 0; $("li").each(function(){ if($(this).attr("class") == "selected") found = 1; }); if(found == 1) { var sel = $("li[class='selected']"); sel.prev().addClass("selected"); sel.removeClass("selected"); } else $("li:last").addClass("selected"); } break; case 13: $("#ajax_response").fadeOut("slow"); $("#keyword").val($("li[class='selected'] a").text()); break; } } } else $("#ajax_response").fadeOut("slow"); }); $("#ajax_response").mouseover(function(){ $(this).find("li a:first-child").mouseover(function () { $(this).addClass("selected"); }); $(this).find("li a:first-child").mouseout(function () { $(this).removeClass("selected"); }); $(this).find("li a:first-child").click(function () { $("#keyword").val($(this).text()); $("#ajax_response").fadeOut("slow"); }); }); }); i'd really appreciate some help with this please... thanks Luke Hi Guys, i am wondering if there is a way to have an auto Complete form field from a db table data ? thanks 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 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 i have a form with several headings, then for each heading i have a list of items with a select box filled with numbers. For each heading a maximum of items is allowed, so the user should change the values in the dropdowns and not be allowed to continue until they are less than or equal to their maximum limit. To complicate this, there will be more than one headings on the page, but each one with a different name/id. Eg: Heading 1 Title 1 DROPDOWN1 Title 2 DROPDOWN2 Title 3 DROPDOWN3 So here the max is 10, so the values cannot exceed 10 Heading 2 Title 1a DROPDOWN1 Title 2a DROPDOWN2 Title 3a DROPDOWN3 Title 4a DROPDOWN4 So here the max is 10, so the values cannot exceed 14 thanks Hello, I need your help. I have 2 checkboxes. How would I control one from the other? Eg. [ ] Option A [ ] Option B - If Option A was checked first and, I put a checkmark in option B then Uncheck Option A and leave option B checked. - If Option B was checked and, I put a check mark in Option A then uncheck Option B and leave Option A checked. How would that be written in Javascript, I am totally confused. Any help with this is much and foremost greatly appreciated. Cheers, J Hi, I have some tickboxes and one is marked Other. So what I would like is when someone put a tick in other, to display 5 textboxes name Other 1 to 5 I presume this is done by javscript, but not sure where to start, can anyone help? Also if possible when they untick it, they disapper, but not a must. Each tickbox is independent from each other. It can also use jQuery or Ajax if that helps 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 everyone, Is there a shorter and cleaner way of performing the following: The objective is to get the value/input from the first set of textboxes in the form and copy them to other set of textboxes. Outline of the form is as follows: First set of textboxes Company Address City State Zip Country Select number of users -->1 2 3 User 1 Company Address City State Zip Country User 2 Company Div Address1 Address2 City State Zip Country User 3 Company Address City State Zip Country ============================================= At the moment the code looks like this where (comp,div, addra,addrb,city,state,zip and country) are the name attributes of the first set of text boxes and (comp1.....country1,comp2.....country2, comp3....country3) are the name attributes for the textboxes for user 1,2 and 3 respectively. Code: function compAddress(){ document.form.comp1.value = document.form.comp.value; document.form.div1.value = document.form.div.value; document.form.addra1.value = document.form.addra.value; document.form.addrb1.value = document.form.addrb.value; document.form.city1.value = document.form.city.value; document.form.state1.value = document.form.state.value; document.form.zip1.value = document.form.zip.value; document.form.country1.value = document.form.country.value; document.form.comp2.value = document.form.comp.value; document.form.div2.value = document.form.div.value; document.form.addra2.value = document.form.addra.value; document.form.addrb2.value = document.form.addrb.value; document.form.city2.value = document.form.city.value; document.form.state2.value = document.form.state.value; document.form.zip2.value = document.form.zip.value; document.form.country2.value = document.form.country.value; document.form.comp3.value = document.form.comp.value; document.form.div3.value = document.form.div.value; document.form.addra3.value = document.form.addra.value; document.form.addrb3.value = document.form.addrb.value; document.form.city3.value = document.form.city.value; document.form.state3.value = document.form.state.value; document.form.zip3.value = document.form.zip.value; document.form.country3.value = document.form.country.value; Thanks, Hi , I have 5 or 6 textboxes and all of them are required ( have required field validators ) .. I want to change their background color to yellow when they are left blank and when the box is filled the backgorund color to white ..Is it possible to do via javascript ..I am a beginer so any help is greatly appreciated I have the following code which adds a dynamically created textbox to a form: Code: function addarow() { if (count > 5) {return false} count ++; addbox = '<input type = "text" name = "txt1" id = "txt1" class = "box">'; document.getElementById("boxes"+count).innerHTML = addbox + "<br>"; } I am having difficulties in assigning different names/ids to the sequential textboxes, that is "txt"+count to give txt1, txt2 etc. Your assistance will be much appreciated. A child of five would understand this. Send someone to fetch a child of five. Groucho Marx 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> 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> Hi all, I create textboxes dynamically by the following code function addElement() { var contentID = document.getElementById('content'); var newTBDiv = document.createElement('div'); newTBDiv.setAttribute('id','strText'+intTextBox); divname='strText'+intTextBox; newTBDiv.innerHTML = "Text "+intTextBox+": <input type='text' id='divid' +intTextBox name='txtbx[]'/>"; intTextBox = intTextBox + 1; contentID.appendChild(newTBDiv); } It works fine,but i want to get the values and validate it so i use the following code.. var idval=new Array(); for(var i=0;i<intTextBox;i++) { idval[i]=document.getElementById('divid').value; alert(idval[i]); } but it didn`t work out,Any suggestions really helpful. Thankyou. I have a piece of JavaScript code that should validate that a username field is not empty or null and that a telephone field is in the correct format using event handler registration. It seems to be validating fine but if there is an error it still manages to submit. HTML Code: <html> <head> <script type = "text/javascript" src = "js/validator.js" > </script> </head> <body> <form id = "decorForm" action = ""> <table border = "0"> <tr> <th>Username: </th> <td> <input type = "text" id = "myUserName" size = "15" maxlength = "15"/> </td> </tr> <tr> <th>Telephone: </th> <td> <input type = "text" id = "telephone" name = "telephone" size = "15" maxlength = "13"/> <br /> (999)999-9999 </td> </tr> <tr> <td> <input type = "submit" value = "Submit" /> </td> <td> <input type = "reset" value = "Reset" /> </td> </tr> </table> </form> <script type = "text/javascript" src = "js/validatorr.js" > </script> </body> </html> JAVASCRIPT (validator.js) Code: function chkUser() { // Verifies that the UserName field is not empty. var myUserName = document.getElementById("myUserName"); if (myUserName.value == "" || myUserName.value == null) { alert ("Please enter a Username!"); return false; } else { return true; } } function chkTelephone() { // Verifies that the Telephone field value is in the correct format. var tel = document.getElementById("telephone"); var pos = tel.value.search(/^\(\d{3}\)\d{3}-\d{4}$/); if (pos != 0) { alert ("Please enter telephone number in the following format: (999)999-9999"); return false; } else { return true; } } function chkFields() { // Verifes all fields and returns boolean to event handler // The event handler function if (chkUser() && chkTelephone()) { return true; } else { return false; } } JAVASCRIPT (validatorr.js) Code: //Register the event handlers for validator.js document.getElementById("decorForm").onSubmit = chkFields; I am trying to use this as an example. <!-- ** 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> I recently started designing websites, I'm pretty good with working in the design area of expertise. However I am not so great at the development part. I have had little to no experience with java programming. I am putting e commerce on my clients site. He is selling an item that varies in price depending on what size it is. What I am trying to do is have a input for the length and the width and then display the price. I have configured the length and width to multiply and can display the total but I don't know what the if then statement would look like for the price. So lets say the user puts in 4 length and 4 width. I can display 16. But I want to take that and say if =16 then display $21.50 or whatever the cost would be. But I cannot figure out how to code it right for the if then part and then the display part. I am very new to java programming and think i might be a little out of my league with this project but any help you can offer would be great. thank you.
<!-- ** 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> |