JavaScript - Best Way To Map Multiples Values To A Pair Of Values
Hi,
What's a good way/ideal data structure to achieve this? The objective of the code/function is to map user-inputted strings into a pair of specific, hard-coded strings. For example, say the user types "firefox" or "ff", or "fx". The output would be the pair ["browser", "mozilla"], for example. I'm currently using a multidimensional array, but it feels inefficient and I'm having trouble mapping an arbitrary number of inputs into 2 outputs. Code: var strings = [ ["input1", "output1a"], ["input2", "output1a"], ["input3", "output1a"], ["input1", "output1b"], ["input2", "output1b"], ["input3", "output1b"] ]; How should I map the elements ["input1", "input2", "input3"] => ["output1a", "output1b"] ? Another method I used previously was a massive switch statement. This fulfills my needs, but I'm not sure about the efficiency (though if I remember correctly, switch statements become more efficient as size grows, since it uses a hash table?). Code: switch (input) { case "ff": case "firefox": case "fx" : case "ffox": return ["browser", "mozilla"]; case "ie": case "internet explorer": return ["browser", "microsoft"]; ... } Similar TutorialsI'm trying to create a modulus function that will redirect users who input certain values to a secondary page. I've searched google and found a way to validate when users input a multiple of x, but I need to take it one step further and only allow values within a certain range. In full, I need to validate multiples of 7 starting at 7007 and ending on 15673 (so validate on 7007, 7014, 7021, etc.). Right now I'm looking at this code: Code: $(document).ready(function(){ $(".sub").click(function(){ if (!(($(".txt").val() % 7 == 0) || ($(".txt").val()==1))) { alert("Not interval of 7 or value of 1"); } else { alert("Interval of 7 or value of 1!"); } }); }); Which I found here. I also need to remove the "value of 1". I'm new to JS, so when I tried, I broke the code. Any help would be much appreciated. Thank you! Hi gud mng, I have one problem... How to process textbox values/ call textbox values in JS through a Java program. My text box values are dates. I have to process these dates. Like in online banking we select day to know our transactions. After submitting we get results. remember my files are in my directory only. No need of database. My files are look like 20100929, 20100930, 20101001 For epoch_classes.js, epoch_styles.css u can download coding from this link : http://www.javascriptkit.com/script/...ch/index.shtml Code: Code: <html> <table width="900" border="0" cellpadding="10" cellspacing="10" style="padding:0"> <tr><td id="leftcolumn" width="170" align="left" valign="top"> <div style="margin-left:0px;margin-top:0px"><h3 class="left"><span class="left_h2">Select Option</span></h3> <a rel="nofollow" target="_top" href="day_wise.htm" >Day-wise</a><br /> <br /> <a rel="nofollow" target="_top" href="between.htm" >Between Days</a> <link rel="stylesheet" type="text/css" href="epoch_styles.css" /> <script type="text/javascript" src="epoch_classes.js"></script> <script type="text/javascript"> var cal1, cal2; window.onload = function () { cal1= new Epoch('epoch_popup','popup',document.getElementById('popup_container1')); cal2= new Epoch('epoch_popup','popup',document.getElementById('popup_container2')); }; /*............*/ function confirmation(f) { var startdate = f.fromdate.value var enddate = f.todate.value var myday=new Date() var yr=myday.getFullYear() var mn=myday.getMonth()+1 var dt=myday.getDate() var today="" var present, ys, ms, ds, ye,me,de, start, end if(mn < 10) { mn = "0" + mn } if(dt <10) { dt = "0" + dt } today= yr + "/" + mn + "/" + dt present=yr + "/" + mn + "/" +dt if (today < startdate ) { alert (" Start date should not be exceed to-day's date " + present ) startdate.focus() return false } if (today < enddate ) { alert (" End date should not be exceed to-day's date " + present ) enddate.focus() return false } if (today == startdate ) { alert(" You are selected to-days date as Starting day" ); } var answer = confirm("Do you want to continue ?") if (answer) { if( startdate < enddate) alert("Dates between " + startdate + " to " + enddate + " are confirmed" ) else alert("Dates between " + enddate + " to " + startdate + " are confirmed" ) } else { alert("Date not confirmed") window.location="to_date.htm"; } ys= startdate.substring(0,4); ms= startdate.substring(5,7); ds= startdate.substring(8,10); start=ys + "" + ms + "" +ds ye= enddate.substring(0,4); me= enddate.substring(5,7); de= enddate.substring(8,10); end=ye + "" + me + "" +de } /*.......................................................*/ </script> <div style="margin-left:100px;"> <body> <style type="text/css"> #conf { margin-left:115px; } </style> <td align="left" valign="top"> <table width="100" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:0px"> </table> <h4>From Date</h4> <form name= "formbet" id="placeholder" method="post" action="#" > <input id="popup_container1" type="text" name= "fromdate" maxlength="10" size="20"/> <td align="left" valign="top"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:20px"> <h4>To Date</h4> <input id="popup_container2" type="text" name= "todate" maxlength="10" size="20"/> <br /> <br /> <input id="conf" type="button" onclick="confirmation(this.form)" value="Submit"> </form> </body> </html> In my coding, ys, ms, ds represents year starting, month starting, starting day... ye, me, de represents end... start,end gives file names in the format of yyyymmdd now i want to process files from 20100101 to 20100930 means from date is 2010/01/01 and to date is 2010/09/30 if i press submit button the files from 20100101 to 20100930 are processes here ys=2010 ms=01 ds =01 and ye=2010 me=09 de= 30 For this how do i call these textbox values (from date text box and todate) to another program (java) Thanks in advance. I have a bunch of checkboxes like below that the user can check some or all and click the button and see the values of all the selected checkboxes. How can I do that? Code: <script> function alertValues(){ } </script> <input type="checkbox" class ="normal2" value="131971" name="list[]" > <input type="checkbox" class ="normal2" value="131973" name="list[]" > <input type="checkbox" class ="normal2" value="131975" name="list[]" > <input type="checkbox" class ="normal2" value="131977" name="list[]" > <input type="button" onClick="alertValues()" Hi, Ihave this html/jscript hybrid and when i run it in firefox the error console says a value is undefined when i click it the very first <html> is highlighted???? any one no why? Hello, I am new here, and I will probably break some of the forum rules on accident and I apologize ahead of time, but please go easy on me. I have a problem with a question in a Javascript class I am taking currently. The book explains how to detect the smallest values the user inputs but does not explain how to detect already declared variables that have values in them and how to detect which of these declared variables has the smallest number. For example: Code: double aA = 3.7; double aB = 5.8; double aC = 1.9; double aD = 7.2; double aMin; // this is the variable I want the program to detect and stick // the smallest variable into. I want the code to detect the variable containing the smallest number and it has to be able to detect negative numbers as well. I am completely lost on how to do this! Any help would be appreciated! Thank you! I have 2 combo boxes where you can move the items in combo box 1 to combo box 2. I want to validate that combo box 2 actually has something moved to it. How can I count the items in combo box 2. Combo box 2 will initially have no items in the box on page load. It is up to the user to move the items to combo box 2 and I want to make sure at least 1 item was moved.
Hi to all, Sorry to ak this question it may be easy but i didn't got the solution on net please provide the proper answer. My question is : I am defining hyperlink in struts as <a href= Javascript:formSubmit(<bean:write name="AA" property="aa">','<bean:write name="BB" property="bb">) defining function as function formSubmit(Aa,Bb) { document.forms[0].action="/accesingpage.do?method=create&AA=+Aa" ----> in above statement how to pass the second parameter(i.e Bb)....I tried different ways but giving syntax error. please post the ans as soon as possible OK, so a bit of an issue... I've done a navigation, that works just wonderfully. There are three dropdowns in the top rown, and one down below. The three on the top populate the one below it. All works fine until.... *dum dum dah dummmm* I wanted to make the bottom box invisible until one of the top onse were selected. The nav script goes as follows: Code: var cacheobj=document.dynamiccombo.stage2 function populate(x){ for (m=cacheobj.options.length-1;m>0;m--) cacheobj.options[m]=null selectedarray=eval(x) for (i=0;i<selectedarray.length;i++) cacheobj.options[i]=new Option(selectedarray[i].text,selectedarray[i].value) cacheobj.options[0].selected=true } populate(combo1) Code: <select name="usstage1" size="1" onchange="showDiv(this.value);window.open(this.options[this.selectedIndex].value,'_top');" > <option selected="selected" value="javascript:populate(combo1)">United States</option> <option value="javascript:populate(combo2)">Alabama</option> <option value="javascript:populate(combo3)">Alaska</option> <option value="javascript:populate(combo4)">Arizona</option> <option value="javascript:populate(combo5)">Arkansas</option> <option value="javascript:populate(combo6)">California</option> etc... Which populates the bottom dropdown Now to hide it, I've done: Code: var lastDiv = ""; function showDiv(divName) { if (lastDiv) { document.getElementById(lastDiv).className = "hiddenDiv"; } if (divName && document.getElementById(divName)) { document.getElementById(divName).className = "visibleDiv"; lastDiv = divName; } } And used a Code: <div id="menudiv" class="hiddenDiv"> around the lower dropdown, which hides it effectively then I modded the upper menu Code: <select name="usstage1" size="1" onchange=" showDiv(this.value); window.open(this.options[this.selectedIndex].value,'_top')" > adding what's in red to call the change Now this is where I'm stuck, how can I get: Code: <option value="menudiv;javascript:populate(combo2)">Alabama</option> the two options in...have tried a couple of different ways and failed horribly eash time...or maybe I'm just going about this completely wrong? i am making a mock website where the user make their own computer by selecting items from drop down menus. then a value of the item comes up below. this works but i am having trouble adding the numbers up for the total cost. here is my code <html><head><title>build</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css"> </style></head> <body> <script type="text/javascript"> var motherboard = new Array( '74', '50', '73', '106', '269', '64', '55', '135', '47', '79', '118', '163'); var cpu = new Array( '88', '104', '168', '352'); function changeMotherboard(Mid) { var ind = document.getElementById(Mid).selectedIndex; document.getElementById("motherboardDisplay").innerHTML=motherboard[ind]; } function changeCpu(Cid) { var ind = document.getElementById(Cid).selectedIndex; document.getElementById("cpuDisplay").innerHTML=cpu[ind]; } </script> </head><body> <form> Motherboard <select id="motherboard" onChange="changeMotherboard('motherboard');"> <option value="0">Asus P5G41C-M-LX G41 DDR2+DDR3</option> <option value="1">MSI G41M-P33 </option> <option value="2">Asus P5P41T-LE </option> <option>G-B H55M-S2H</option> <option>Asus P7P55D-E-Deluxe</option> <option>Asus M2N68-AM Plus </option> <option>ASRock N68S3-UCC </option> <option>Asus M4A88TD-M-EVO-USB3</option> </select><br> </form> <div id="motherboardDisplay">Select from the list to see price</div> <form> CPU <select name="cpu" id="cpu" onChange="changeCpu('cpu');"> <option value="0">E6500</option> <option value="1">Core G6950</option> <option value="2">i3-550</option> <option>Core i7-930</option> </select> <br> </form> <div id="cpuDisplay" type = text>Select from the list to see price</div> <p> </p> <p> </body> </html> Hello, I have following javascript that loads a streetmap: Code: <script type="text/javascript"> geoportaal_type = "gemeente"; geoportaal_id = "blankenberge"; geoportaal_startupmodule = "stratenatlas"; geoportaal_bgcolor = "FFFFFF"; </script> <script type="text/javascript" src="http://www.geoportaal.be/syndication/toonportaal.js"></script> What I want to do is pretty simple: create a little searchbox on my homepage where people can enter their streetname and housenumber and the map loads. To do this i use following code related to a script: Code: <script type="text/javascript"> geoportaal_niscode = "vilvoorde"; geoportaal_startupmodule = "stratenatlas"; geoportaal_bgcolor = "FFFFFF"; geoportaal_request_name = "toonadres"; geoportaal_request_parameters = "straat=Kerkstraat&huisnr=1"; </script> <script src="http://www.geoportaal.be/syndication/toonportaal.js"></script> Basically the same as mentioned earlier, though some other tags must be used. How do I create the fields (values) to enter the text and the OK-button to confirm the search? When users press the OK-button the script must load. When loading, following values are important: geoportaal_request_parameters = "straat=Kerkstraat&huisnr=1where straat=VALUE1&huisnr=VALUE2 So: VALUE1=streetname VALUE2=housnumber All I need is the script to take the values entered by the users and to paste these values on the right place (code above). How do i do this, do i need an onclick-handler for this? This is html-code for the searchbox but no actions are defined yet: Code: <div id=locationsearch> <table id="form"> <tr><td>Straatnaam:</td><td><form id="form1" name="form1" method="post" action=""> <label> <input type="text" name="straat" id="VALUE1" /> </label> </form></td></tr> <tr><td>Huisnummer:</td> <td><form id="form2" name="form2" method="post" action=""> <label> <input type="text" name="huisnr" id="VALUE2" /> </label> </form></td></tr> <tr><td> </td><td><form id="form3" name="form3" method="post" action=""> <label> <input type="submit" name="toonadres" id="toonadres" value="Lokaliseer" /> </label> </form></td></tr> </table> </div> Please advise from A to Z. I'm a novice. Thank you in advance, William. hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Can someone please tell me how I would modify the following function to get it to check if a url variable is present and if so to add it into the string variable for the url. Code: function ajaxFunction(pagenum){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } var drop_1 = document.getElementById('drop_1').value; var model = document.getElementById('model').value; var mileage = document.getElementById('mileage').value; var colour = document.getElementById('colour').value; var age = document.getElementById('age').value; var min_price = document.getElementById('min_price').value; var max_price = document.getElementById('max_price').value; var min_engine_size = document.getElementById('min_engine_size').value; var max_engine_size = document.getElementById('max_engine_size').value; //var pics = document.getElementById('pics').value; if (document.getElementById("pics").checked==true) { var photos = "Yes"; } else { var photos = "No"; } var keywords = document.getElementById('keywords').value; var queryString = "?drop_1=" + drop_1 + "&model=" + model + "&mileage=" + mileage + "&colour=" + colour + "&age=" + age + "&min_price=" + min_price + "&max_price=" + max_price + "&min_engine_size=" + min_engine_size + "&max_engine_size=" + max_engine_size + "&photos=" + photos + "&keywords=" + keywords + "&page=" + pagenum; ajaxRequest.open("GET", "filtered.php" + queryString, true); ajaxRequest.send(null); } If my url is index.php?make=Apolo then I need to get this added into the var queryString part of the function so that the ajax returns the correct values. Any help would really be appreciated, I'm fairly new to js. Hello Thanks to those people on this Forum who have provided me with help, along with my little knowledge of Javascript I have been able to create the basis of a form for my Skittle League which will allow teams to submit results over the web. I have one calculation to complete before I look to make the form live and I am hoping someone can provide the final peice of the jigsaw. The scoresheet can be found at http://www.stroudskittles.co.uk/test/scorecard.html The form adds togther the 5 values for each half for each team and places them in a Half Total box below. The form adds together the two totals for each half for each team then places them in a Total box below I have been able to add a operation using the onchange event the points are automatically calculated for each half and total, depending on the overall scores, 2 points for a win, 1 for a draw 0 for a loss. What I'm struggling to do is add the three points totals together to generate the Overall Points for a team and place them in a text box at the top of the scoresheet (marked xxx on the page). Can anyone suggest the best method to do this. Also is it possible to combine the sums into one script therefore reduing the overall size. Your help very much appreciated Hi all, I'm using a nifty little form-dependency script (http://www.dynamicdrive.com/dynamici...dependency.htm) that will hide certain form fields depending on the answer to previous fields on the form. Basically, I can make a field hide/appear for users with JS enabled; for example, if the field "Instrument1" is answered "Oboe" then this new field that I designate will appear: Code: <input type="hidden" class="DEPENDS ON Instrument1 BEING Oboe" /> What I really want to do is use JavaScript to manipulate Instruemnt1 do that it will work with Instrument1, Instrument2, Instrument3, all the way through Instrument10. If any one of those 10 "Instrument*" fields are answered "Oboe". Thanks for reading. Hi Guys, How do I sum the values of an array and output the result using document.write? Say my array is var number=new Array(1.234,56.43,1.02); THANKS Thought this wud work? Code: <script type="text/javascript"> var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(sum(x)); </script> I sell products on amazon. and ASINs are Amazon Identifiers for products. So If I want to check out my product pages I have to go to "www.amazon.co.uk/dp/ "I have to put an ASIN here" . If I can put everything together in the text box and hit go it should take me to the first page(first ASIN). Here is a sample ASIN B004Z2QORW I have the code below but I somehow cant get it to work. Please help. I haven't assigned anything to the go button. I will put a list of ASINs in the text area and the iframe should concatenate the value from a row to the hardcoded URL and when I click next it should concatenate the value from the next row; when I click previous the value from the previous row. Code: <HTML> <Head> <H1 align="center">Detail Page Lookup using ASINs</H1> </head> <body> <textarea rows="10" cols="20" value=""> ASINs here </textarea> <button id="go">Go</button> <button id="prev" align="right">Previous</button> <button id="next" align="right">Next</button> <br/> <iframe id="myframe" src="http://www.amazon.co.uk/dp/" height="100%" width="100%"> <p>Your browser does not support iframes.</p> </iframe> <script>var domain='http://www.amazon.co.uk/dp/'; $('#prev, #next').on('click', function(e) { var Myval = $('textarea').val().split('\n'), now = $('#myframe').attr('src').replace(domain, ''); if (Myval.indexOf(now)==-1) { var src=domain+Myval[0]; }else{ var p = Myval.indexOf(now)!==0 ? Myval.indexOf(now)-1 : Myval.length-1, n = Myval.indexOf(now)==(Myval.length-1) ? 0 : Myval.indexOf(now)+1, src = e.target.id=='next' ? domain+Myval[n] : domain+Myval[p]; } $("#myframe").attr('src', src); console.log(src); }); ? </script> </body> </HTML> Hi There, I need your help. I am capable of getting all the field headers in my excel document but am now unable to get their respective field values. Any idea as to what I am doing wrong? Code: //======================================================================== function v8_export() { //======================================================================== var excel = new ActiveXObject("Excel.Application") var book = excel.Workbooks.Add() var sheet = book.Sheets(1); //sheet.Range("A2").Value = "Hello World" //WRITE COLUMN HEADERS: sheet.Columns("A:P").ColumnWidth = '15' for (var c = 0; c < rs.fields.count; ++c) { sheet.Cells(4, c + 1).Value = rs.fields(c).name } //WRITE FIELD VALUES: var row = 1 for (var c = 0; c < rs.fields.count) { sheet.range('A' + row).value = rs.fields(c).value row = row + 1 } rs.MoveNext excel.Visible = true }//end of function v8_export() Thanks. J I'm new to js and have been going crazy trying to get this to work. I need the script to pull the values in the class selected, then spit out the sum of them. It can't be that hard! This is what I have and it just won't run. I'm working in a intra environment, so I'm not too worried about cross-browser compatibility. Any help would be appreciated. Thank you. <html> <head> <script> function findTheOddOnes() { var theOddOnes = document.getElementsByClassName("odd"); for(var i=0; i<theOddOnes.length; i++){ sum += theOddOnes[i].textContent; alert(sum); } } </script> </head> <body> <h1>getElementsByClassName Test</h1> <p class="odd">1000</p> <p>This is an even para.</p> <p class="odd">1000</p> <p>This one is not odd.</p> <form> <input type="button" value="Find the odd ones..." onclick="findTheOddOnes()"> </form> </body> </html> |