JavaScript - Changing Textbox Value To Represent The Value Of My Autosuggest Value. Please Help!!
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 Similar TutorialsLooking to create a text box in a form that will automatically change value when a certain value is entered. IE: User entering 11111 in to the text box changes text box automatically to 22222. I haven't had much success searching the internet for a code that would do this. Thanks for the help. 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 I 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 Guys, i am wondering if there is a way to have an auto Complete form field from a db table data ? thanks Hi.. I have form and i want to input data using barcode and it will display on textbox and after input on the first textbox the focus will go to next textbox untill it will go on the last textbox and on the last textbox it will automatically save the data's on the database. How is it possible? here is my sample code: Code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <html> <head> <script type="text/javascript"> function ini() { // Retrieve the code var code =document.getElementById ("code_read_box1").value; var code =document.getElementById ("code_read_box2").value; var code =document.getElementById ("code_read_box3").value; var code =document.getElementById ("code_read_box4").value; var code =document.getElementById ("code_read_box5").value; var code =document.getElementById ("code_read_box6").value; // Return false to prevent the form to submit return false; } </script> </head> <body onLoad="document.barcode.code_read_box1.focus()"> <form name=barcode onsubmit = "return ini()"> <input type="text" id="code_read_box1" value="" /><br/> <input type="text" id="code_read_box2" value="" /><br/> <input type="text" id="code_read_box3" value="" /><br/> <input type="text" id="code_read_box4" value="" /><br/> <input type="text" id="code_read_box5" value="" /><br/> <input type="text" id="code_read_box6" value="" /><br/> </form> </body> </html> Hello. I've been teaching myself HTML and CSS for a while, and now I've moved into the world of Javascript (but I'm still very much a beginner). For practice, I've been building a sample sign up form for a mock website, and I'm having problems with the birthdate section. The idea I had was to have MM, DD, and YYYY be the default values of my 3 textboxes (as an example for users), then set the value to nothing when the box gained focus. That all works fine, but I ran into problems when I tried to write an if statement to set the value back to MM, DD, or YYYY if the value was still nothing when the user clicked away. As it is now it just replaces the text inputted into the textbox (which of course is not good). Any ideas for what the problem might be? Code: <form name="signup" action="javascript:void(0);" method="post"> <table> <tr> <td>Date Of Birth:</td> <td> <input name="DOBmonth" type="text" value="MM" size="2" style="color: #555555;" onFocus="clearDOBmonth()" onBlur="restoreDOBmonth()" /> <input name="DOBday" type="text" value="DD" size="2" style="color: #555555;" onFocus="clearDOBday()" /> <input name="DOByear" type="text" value="YYYY" size="4" style="color: #555555;" onFocus="clearDOByear()" /></td> </tr> <tr> <td></td> <td><button name="Submit" type="submit" style="font-size: 1em;">Sign Up</button></td> </tr> </table> </form> <script type="text/javascript" language="javascript"> <!-- document.signup.DOBmonth.value="MM"; document.signup.DOBday.value="DD"; document.signup.DOByear.value="YYYY"; function clearDOBmonth() { document.signup.DOBmonth.value="";} function clearDOBday() { document.signup.DOBday.value="";} function clearDOByear() { document.signup.DOByear.value="";} function restoreDOBmonth() { if ('document.signup.DOBmonth.value = ""') { document.signup.DOBmonth.value = "MM"; // alert(document.signup.DOBmonth.value); } } //--> </script> Another side question, if I set a variable equal to the value of a textbox, then change the value of the variable, does that also change the value of the textbox? or is the variable no longer associated with the textbox. Example: Code: var a = document.form.textbox.value; a = blue; does document.form.textbox.value = blue? or is var a now completely independent of the textbox value? Thanks! Hi, i got a textbox with a submit button but when submit button is clicked it works but it reloads the page. is possible to submit without reload the page? thanks how would you make a function that cheks if any text is in a text box.
OK, my javascript is not that good. So I need your help! I need to create a text box that will only work if a certain code is entered. So if 1234 is in the text box and submit is clicked, then it will take you to the site. IF not then it will print "Please enter correct code" next to the submit button. Here is what I have so far: <input name="txtBox" type="text"/> <input name="btnButton" type="button" value="Submit" onclick="return checkValue()" /> <script type="text/JavaScript"> function checkValue() { var secretcode = document.getElementById("txtBox"); if (secretcode == "1234") { document.location.href = 'secret.html'; } } </script> Thank you for your help! Hey guys, I recently found a small code in internet which use option value in select tag to insert value in text box, so text box has the exact same value as selected option: Code: <form name="theform" onsubmit="CheckForm()"> <select name="myOptions" onchange="document.theform.showValue.value=this.value"> <option name="(some dynamic text)" id="(some dynamic text)" value="I am the first option">I am the first option</option> <option name="(some dynamic text)" id="(some dynamic text)" value="I am the second option">I am the second option</option> <option name="(some dynamic text)" id="(some dynamic text)" value="I am the third option">I am the third option</option> <option name="(some dynamic text)" id=""(some dynamic text)" value="I am the third option">I am the fourth third option</option> </select> <input type="text" name="showValue"><br> </form> Now what I want is simple and a little different from this one, I want the text box value to be as exact as selected option name or id (doesn't matter which one) which means if an option selected, text box value has to follow that option name or id. Thanks folks. Hi, I am having a very difficult time trying to get my text box to validate. I successfully validated my first program using prompts but now when I am using a HTML form I cannot get it to work. I have spent hours upon hours trying to get this working, any help would be greatly appreciated. Code: <html> <head> <title></title> <script type="text/javascript"> function validateform() { var temp = document.forms["inputform"]["temperature"].value while ((isNaN(temp)) || (temp == "")) { alert("Please enter a number"); return false; } if (parseFloat(temp) > 35) { alert("Wow, it's really hot!"); } else if (parseFloat(temp) <= 35) && (parseFloat(temp) >= 18)) { alert("It's a comfortable temperature right now"); } else if (parseFloat(temp) < 18) { alert("Brrr, it's a little bit cold for my liking"); } else { alert("Goodbye, and thanks for using TempReader"); } } </script> </head> <body> <form name="inputform" method="post" action=""> <table> <tr><td>What Is The Temperature?</td><td><input type="text" name="temperature"></td></tr> <!-- Below is submit button that when pressed validates the form --> <tr><td></td><td><input type="submit" value="Submit Details" onclick = validateform()></td></tr> </table> </form> </body> </html> Hi, I have a text-box where you enter the phone nos. On key-press, i have written a validation code to enter only nos and "-". I have disabled Ctrl+v, but my customer want to enable ctrl+v for that text-box only. My requirement is after pasting the value it should automatically check for validation.. How to do it? Thanks... hi, I am tring to display some texts in a textbox using \n to create a new line but it does not work. PHP Code: <script> document.getElementById("txtbox1").value=" this is my firstline \n This is my second line \n this is my third line" </script> <input type="text" id="txtbox1"> thanks Hi there, I have two textboxes and I want some images to be displayed in my textboxes randomly if randomNumber==1 let textbox1/textbox2 backgroundimage change and if randomnumber==2 let textbox1 backgroundimage change again. I think I need some fixing in the following lines: document.getElementById("txtbox1").Attributes.Add("this.style.backgroundImage = 'url(1.jpg)';"); Thanks for any help.. PHP Code: <script> setInterval("showimages()",500); function showimages() { var rno=Math.floor(Math.random()*2)+1; document.getElementById("box1").value=rno; if(rno==1){ document.getElementById("txtbox1").Attributes.Add("this.style.backgroundImage = 'url(1.jpg)';"); document.getElementById("txtbox2").Attributes.Add("this.style.backgroundImage = 'url(2.jpg)';"); } if(rno==2){ document.getElementById("txtbox1").Attributes.Add("this.style.backgroundImage = 'url(3.jpg)';"); document.getElementById("txtbox2").Attributes.Add("this.style.backgroundImage = 'url(4.jpg)';"); } } </script> <input type="text" id="txtbox1" style="position:absolute;top:200px;left:200px;height:150px"> <input type="text" id="txtbox2" style="position:absolute;top:200px;left:500px;height:150px"> <input type="text" id="box1" style="position:absolute;top:100px;left:100px;width:40px;"> <input type="button" onclick='location.reload()' style="position:absolute;top:20px;left:100px;"> I would like to type something into my textbox and then press ENTER, it will execute a function. I tried onFocus, onChange and onBlur but it doesn't do what I want it to. Here's an example I use for onChange. Code: Application: <input type="text" onchange="execProg(0);"> Any comments or suggestions is greatly how can i pass the var to textboxes Code: var win = 0; var loss = 0; var draw = 0; if (c == u) { draw++; return "It's a draw"; } else if ((c == "Fire") && (u == "Air")) { loss++; return "You Lose, Fire beats Air!"; } else if ((c == "Fire") && (u == "Earth")) { draw++; return "It's a draw!"; } else if ((c == "Fire") && (u == "Water")) { win++; return "You Win, Fire is beaten by Water!"; } <tr><td><input type=text size=5 name=w ></td><td>win</td></tr> <tr><td><input type=text size=5 name=l></td><td>loss</td></tr> <tr><td><input type=text size=5 name=d></td><td>draw</td></tr> Hello How am I able to add a a cross to the right of a textbox which once click it clears the text from the textbox, sort of like the way Google do it, I have been trying to do this for ages now and can't seem to find a way to do it. Any help welcome, thank you. - DJCMBear hi, I would to validate a textbox, and limit it to 3alphabets and 3 numbers. That is after the user have input 3 alphabets, he can only enter 3 numbers and nothing more. Can someone help me out? |