JavaScript - Changing Numbers In Forms
Not sure if I should post this in javascript or HTML section, but I have what seems to be a pretty simple script that I'm stumped on.
Basically what I have to do is use onChange to make the second box equal 3 times the first and the third equal the cube of the first. Here's what I have so far, it doesn't do anything: 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>Untitled Document</title> <script type="text/javascript"> function recalcTextBoxes() { // Make sure both boxes have a value if (TextBox1.value != "" ) { // if both boxes have a value calculate for box 3 TextBox2.value = TextBox1.value*3 ; TextBox3.value = TextBox1.value*TextBox1.value*TextBox1.value; } } function recalcTextBoxes2() { if (TextBox2.value!=""){ TextBox1.value= Textbox2.value/3; TextBox3.value=TextBox1.value*TextBox1.value*TextBox1.value; } } function recalcTextBoxes3(){ if (TextBox3.value!=""){ TextBox1.value= Math.pow(TextBox3.value, 1/3); TextBox2.value= Textbox1.value *3; } } </script> </head> <body> <FORM ACTION="../cgi-bin/mycgi.pl"> First <input type=TEXT name="TextBox1" onChange="recalcTextBoxes()" > Second <INPUT TYPE=TEXT NAME="TextBox2" onChange = "recalcTextBoxes2()" > Third <INPUT TYPE=TEXT NAME="TextBox3" onChange = "recalcTextBoxes3()" > </FORM> </body> </html> Anybody have any hints on what I should do next? I'm really new with javascript and HTML so I don't really know what I'm doing. Similar TutorialsIs there any way to convert a number stored as a javascript variable into words? Something like... Code: var num=120394; then run that var through a function and have the output be: One hundred twenty thousand three hundred ninety four Any help would be great! I'm using the autofill forms plugin for firefox which can be found he https://addons.mozilla.org/en-US/firefox/addon/4775 I use it to automatically fill various web forms, duh. But I would like certain values to be chosend randomly from a list I create. I contacted the developer and he said the add on probably does not need a new feature because there is a 'dynamic tags' function to fill certain forms with dynamic values (e.g. the current time or date). He has given over the project to another developer and told me I probably would find a solution in a good javascript programming forum. So here I am! Can anyone help me with this? Basically, I just need a javascript code which chooses on item from an array randomly, I guess? I'm not a programmer myself, so any help would be greatly (!) appreciated. Thanks a lot in advance for any further guidance! Note: Here are sample dynamic tags from the plugin: <datetime> new Date().toLocaleString() <useragent> navigator.userAgent <langcode> navigator.language <resolution> screen.width+'x'+screen.height <clipboard> this.getClipboardText() I have written below code to except only number in a textbox. This is working fine. However, When I'm copying and pasting, then it is taking non-numbers. Code: <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <SCRIPT type="text/javascript"> function isNumberKey1(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode = 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </head> <body> Phone number : <input type="text" id="phonenumber" onkeypress="return isNumberKey1(event)" maxlength="10" size="15" > <br /> <br /> Alternative number: <input type="text" onkeypress="return isNumberKey1(event)" id="alt" maxlength="10" size="15"> <input type="button" value="Submit"> </body> </html> I'm trying to teach myself Javascript to prepare for it next term. I asked earlier how to add together the numbers 1-10 in a loop. Now I'm wondering how can I change the 10 to be a valuable I input. Basically I want to be able to enter a number on the page or in a message box then I want the code to add all the numbers from 1- the number I enter. The code I got from my previous thread is he Code: <html> <head> <script type="text/javascript"> var varX = user input; function sum() { var varX = user input; for(varY = 1; varY<=10; varY++) { varX = varX + varY; } return varX; } var resultat = sum(); alert(resultat); // show message box with result </script> </head> <body> </body> </html> say cutcost2 is 10 and qty is 25 Code: document.profile_quote.cuttotal.value = eval(document.profile_quote.cutcost2.value + document.profile_quote.qty.value) .toFixed(2) the output i get is 1025 rather than 35. what have i got wrong? thanks Hay! I have a silly question, I have a row of numbers, 1 to 250. The numbers are all in one horizantal line. But I want to use a <br> after every 10 numbers. I tried: if(i % 10) { document.write("<br>"); } This is how I wanted to be: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, Does any one know how can I achieve this I'm still a noob. Hi, I have this bit of java code that puts a random/unique number in a field on my web page: <html> <head> </head> <body> <form> <input type="text" name="MyField" /> </form> <script langueage="javascript" type="text/javascript"> var d = new Date(); var tm = d.getTime(); document.getElementsByName('MyField')[0].value=tm; </script> </body> </html> My problem is that I want to limit the number to just 6 digits. Is this possible? Any help would be much appreciated Thank you Dave Hi, I am trying to modify this poetry generator script: Poem Generator .js-file: PHP Code: // Poem Generator JavaScript // Keith Enevoldsen, thinkzone.wlonk.com random_count=0; nsentences=0; nwords1=0; nwords2=0; nwords3=0; nwords4=0; nwords5=0; nwords6=0; nwords7=0; nwords8=0; nwords9=0; function init(form) { form.Samples.selectedIndex=1; generate_input(form, form.Samples.options[form.Samples.selectedIndex].text); make_poem(form); } function generate_input(form, sample_name) { form.title1.value = "Concrete Nouns"; form.title2.value = "Abstract Nouns"; form.title3.value = "Transitive Verbs"; form.title4.value = "Intransitive Verbs"; form.title5.value = "Adjectives"; form.title6.value = "Adverbs"; form.title7.value = ""; form.title8.value = ""; form.title9.value = "Interjections"; form.sentences.value = "The 5 1 6 3s the 1." +"\n5, 5 1s 6 3 a 5, 5 1." +"\n2 is a 5 1." +"\n9, 2!" +"\n1s 4!" +"\nThe 1 4s like a 5 1." +"\n1s 4 like 5 1s." +"\nWhy does the 1 4?" +"\n4 6 like a 5 1." +"\n2, 2, and 2." +"\nWhere is the 5 1?" +"\nAll 1s 3 5, 5 1s." +"\nNever 3 a 1." ; if (sample_name == "Sea") { form.list1.value = "sea\nship\nsail\nwind\nbreeze\nwave\ncloud\nmast\ncaptain\nsailor\nshark\nwhale\ntuna\nseashell\npirate\nlad\ngirl\ngull\nreef\nshore\nmainland\nmoon\nsun"; form.list2.value = "adventure\ncourage\nendurance\ndesolation\ndeath\nlife\nlove\nfaith"; form.list3.value = "command\nview\nlead\npull\nlove\ndesire\nfight"; form.list4.value = "travel\nsail\nwave\ngrow\nrise\nfall\nendure\ndie"; form.list5.value = "big\nsmall\nold\ncold\nwarm\nsunny\nrainy\nmisty\nclear\nstormy\nrough\nlively\ndead"; form.list6.value = "swiftly\ncalmly\nquietly\nroughly"; form.list7.value = ""; form.list8.value = ""; form.list9.value = "o\noh\nooh\nah\nlord\ngod\nwow\ngolly gosh"; } else if (sample_name == "City") { form.list1.value = "street\nsidewalk\ncorner\ndoor\nwindow\nhood\nslum\nskyscraper\ncar\ntruck\nguy\ngirl\njob\nflower\nlight\ncigarette\nrain\njackhammer\ndriver\nworker"; form.list2.value = "action\nwork\nnoise\ndesolation\ndeath\nlife\nlove\nfaith\nanger\nexhaustion"; form.list3.value = "get\ngrab\nshove\nlove\ndesire\nbuy\nsell\nfight\nhustle\ndrive"; form.list4.value = "talk\ngab\nwalk\nrun\nstop\neat\ngrow\nshrink\nshop\nwork"; form.list5.value = "big\nsmall\nold\nfast\ncold\nhot\ndark\ndusty\ngrimy\ndry\nrainy\nmisty\nnoisy\nfaceless\ndead"; form.list6.value = "quickly\nloudly\ncalmly\nquietly\nroughly"; form.list7.value = ""; form.list8.value = ""; form.list9.value = "o\noh\nooh\nah\nlord\ngod\ndamn"; } else { clear_all(form); } form.outtext.value = ""; count_all_lines(form); } function clear_all(form) { form.Samples.value = "-"; form.title1.value = ""; form.title2.value = ""; form.title3.value = ""; form.title4.value = ""; form.title5.value = ""; form.title6.value = ""; form.list1.value = ""; form.list2.value = ""; form.list3.value = ""; form.list4.value = ""; form.list5.value = ""; form.list6.value = ""; form.list7.value = ""; form.list8.value = ""; form.list9.value = ""; form.sentences.value = ""; form.outtext.value = ""; count_all_lines(form); } function count_all_lines(form) { nwords1 = count_lines(form.list1); nwords2 = count_lines(form.list2); nwords3 = count_lines(form.list3); nwords4 = count_lines(form.list4); nwords5 = count_lines(form.list5); nwords6 = count_lines(form.list6); nwords7 = count_lines(form.list7); nwords8 = count_lines(form.list8); nwords9 = count_lines(form.list9); nsentences = count_lines(form.sentences); } function random(maxnum) { r = Math.floor(Math.random() * maxnum) + 1; if (r > maxnum) r = maxnum; return r; } function count_lines(txt) { str = txt.value; len = str.length; nword = 1; for (i = 0; i < len; i++) { if (str.charAt(i) == "\n") { nword++; } } if (str.charAt(len-1) == "\n") nword--; return nword; } function get_line(str, lnum) { len = str.length; iline = 1; ichar = 0; jchar = -1; for (i = 0; i < len; i++) { if (str.charAt(i) == "\n") { iline++; if (iline == lnum) { ichar = i + 1; } else if (iline == (lnum + 1)) { jchar = i - 1; if (str.charAt(jchar) == "\r") { jchar--; } break; } } } if (jchar < 0) jchar = len - 1; // Note: Use loop because substr() doesn't work consistently on old browsers s = ""; for (i = ichar; i <= jchar; i++) { s = s + str.charAt(i); } return s; } function initial_cap(str) { // Note: Use loop because substr() doesn't work consistently on old browsers len = str.length; s = ""; for (i = 0; i <= len; i++) { if (i == 0) { s = s + str.charAt(i).toUpperCase(); } else { s = s + str.charAt(i); } } return s; } function make_poem(form) { form.outtext.value = ""; count_all_lines(form); nlines = random(4) + 1; for (ilin = 1; ilin <= nlines; ilin++) { make_poem_line(form) } } function make_poem_line(form) { pattern = get_line(form.sentences.value, random(nsentences)); lenpat = pattern.length; for (ichr = 0; ichr < lenpat; ichr++) { chr = pattern.charAt(ichr); // If the pattern contains a digit n, then pick a random word from list n if ((chr >= '1') && (chr <= '9')) { if (chr == '1') { wrd = get_line(form.list1.value, random(nwords1)); } else if (chr == '2') { wrd = get_line(form.list2.value, random(nwords2)); } else if (chr == '3') { wrd = get_line(form.list3.value, random(nwords3)); } else if (chr == '4') { wrd = get_line(form.list4.value, random(nwords4)); } else if (chr == '5') { wrd = get_line(form.list5.value, random(nwords5)); } else if (chr == '6') { wrd = get_line(form.list6.value, random(nwords6)); } else if (chr == '7') { wrd = get_line(form.list7.value, random(nwords7)); } else if (chr == '8') { wrd = get_line(form.list8.value, random(nwords8)); } else if (chr == '9') { wrd = get_line(form.list9.value, random(nwords9)); } else { wrd = ''; } // Capitalize first letter of sentence if (ichr == 0) { wrd = initial_cap(wrd); } form.outtext.value = form.outtext.value + wrd; } else { form.outtext.value = form.outtext.value + chr; } } form.outtext.value = form.outtext.value + "\n"; } And the .html: PHP 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=windows-1252"> <title>Poem Generator</title> <meta name="Description" content="Poem Generator"> <meta name="Keywords" content="Poem Generator"> <meta name="robots" content="all"> <link rel="icon" href="http://thinkzone.wlonk.com/thinkzone_icon.png"> <link rel="stylesheet" href="Poem%20Generator_files/style.css" type="text/css"> <script type="text/javascript" src="Poem%20Generator_files/PoemGen.js"></script> </head> <body onload="init(document.form)" style="background-color: #99CC99;"> <div class="bodydiv" style="background-color: #99CC99;"> <div align="center"> <a href="http://thinkzone.wlonk.com/index.htm"><img alt="thinkzone.wlonk.com" src="Poem%20Generator_files/thinkzone_wlonk_trans.png"></a> <h2>Poem Generator</h2> <p>This makes random poems. First, it randomly selects sentence patterns. Then, wherever the pattern has a number, it randomly selects a word from one of the numbered word lists. You can either choose one of the sample sets of words and sentence patterns, or you can enter your own words and sentence patterns.</p> <form name="form" id="form" action=""> <input value="Make Poem" onclick="make_poem(this.form)" type="button"><br> <textarea cols="70" rows="6" name="outtext">Grow swiftly like a clear wind. The reef falls like a rough sun. </textarea><br> <br> <b>Word Lists</b><br> Samples: <select name="Samples" onchange="generate_input(this.form, this.options[this.selectedIndex].text)"> <option>-</option> <option selected="selected">Sea</option> <option>City</option> </select> <input value="Clear Lists" onclick="clear_all(this.form)" type="button"><br> <table> <tbody> <tr> <th>1</th> <th>2</th> <th>3</th> <th>4</th> <th>5</th> <th>6</th> <th>7</th> <th>8</th> <th>9</th> </tr> <tr> <td><textarea cols="12" rows="2" name="title1">Concrete Nouns</textarea></td> <td><textarea cols="12" rows="2" name="title2">Abstract Nouns</textarea></td> <td><textarea cols="12" rows="2" name="title3">Transitive Verbs</textarea></td> <td><textarea cols="12" rows="2" name="title4">Intransitive Verbs</textarea></td> <td><textarea cols="12" rows="2" name="title5">Adjectives</textarea></td> <td><textarea cols="12" rows="2" name="title6">Adverbs</textarea></td> <td><textarea cols="12" rows="2" name="title7"></textarea></td> <td><textarea cols="12" rows="2" name="title8"></textarea></td> <td><textarea cols="12" rows="2" name="title9">Interjections</textarea></td> </tr> <tr> <td><textarea cols="12" rows="10" name="list1">sea ship sail wind breeze wave cloud mast captain sailor shark whale tuna seashell pirate lad girl gull reef shore mainland moon sun</textarea></td> <td><textarea cols="12" rows="10" name="list2">adventure courage endurance desolation death life love faith</textarea></td> <td><textarea cols="12" rows="10" name="list3">command view lead pull love desire fight</textarea></td> <td><textarea cols="12" rows="10" name="list4">travel sail wave grow rise fall endure die</textarea></td> <td><textarea cols="12" rows="10" name="list5">big small old cold warm sunny rainy misty clear stormy rough lively dead</textarea></td> <td><textarea cols="12" rows="10" name="list6">swiftly calmly quietly roughly</textarea></td> <td><textarea cols="12" rows="10" name="list7"></textarea></td> <td><textarea cols="12" rows="10" name="list8"></textarea></td> <td><textarea cols="12" rows="10" name="list9">o oh ooh ah lord god wow golly gosh</textarea></td> </tr> </tbody> </table> <br> <b>Sentence Patterns</b><br> <textarea cols="40" rows="10" name="sentences">The 5 1 6 3s the 1. 5, 5 1s 6 3 a 5, 5 1. 2 is a 5 1. 9, 2! 1s 4! The 1 4s like a 5 1. 1s 4 like 5 1s. Why does the 1 4? 4 6 like a 5 1. 2, 2, and 2. Where is the 5 1? All 1s 3 5, 5 1s. Never 3 a 1.</textarea></form> <p>You can see the JavaScript source code in PoemGen.htm and PoemGen.js.</p> </div> <hr> <div align="center"> <a href="http://thinkzone.wlonk.com/index.htm">Keith Enevoldsen's Think Zone</a> </div> </div> </body></html> What I want to do is add more word lists. This of course is easy in principle - I can just continue the lists like: form.title9.value = ""; form.title10.value = ""; form.title11.value = ""; - and so on. The problem is that, in the "sentence patterns", I cannot use numbers with two digits to refer to the word lists. Then it thinks I mean 1+0 and 1+1 instead of 10 and 11. How can I allow this? I have heard about using regular expressions to "capture the number by its word boundary" - is this a good solution? If yes, can someone please explain to me how to do it? (I have tried special characters like @,#,$ and more as well as Russian and Greek letters. This makes the script unable to generate poems.) Thank you. Reply With Quote 12-28-2014, 08:31 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts Convert the string values which are concatenated by + (e.g. "2" + "5" = 25) into numbers (e.g. 2+5 = 7) by using the Number() method, or another way is to multiply the value by 1. But you are using string values if (chr == '1') { quite unnecessarily. Remove the quote marks to make them into numbers. "1" is a string value. 1 is a number Obviously chr = pattern.charAt(ichr); only captures a single numeric chararcter. You can extract two-digit numbers from a string just by removing all non-digits var x = str.replace(/[^0-9]/g,""); // strip all characters but digits That of course assumes that there is only one number in the string. Haikus are easy But sometimes they don't make sense. Refrigerator. Hi, greeting all. could you help me please to edit this javascript, I'd like to add a message alert if the values stopped on (777) Live Demo Code: <script language="JavaScript"> function begin() { i=0; document.form.col1.value="V"; document.form.col2.value="V"; document.form.col3.value="V"; roll(speed); } function roll(speedB) { if (document.form.col1.value=="V") { document.form.a1.value=Math.floor(Math.random()*9) +0 ; } if (document.form.col2.value=="V") { document.form.a2.value=Math.floor(Math.random()*9)+0 ; } if (document.form.col3.value=="V") { document.form.a3.value=Math.floor(Math.random()*9)+0 ; } timerid=setTimeout("roll("+speedB+")",speedB); } function stop(col) { if ( col==1) if(document.form.col1.value!=" "){ document.form.col1.value=" ";i++;} if ( col== 2) if(document.form.col2.value!=" "){ document.form.col2.value=" ";i++;} if ( col==3) if(document.form.col3.value!=" "){ document.form.col3.value=" ";i++;} // speedB=500000;roll(speedB); } </script> Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> </head> <script type = "text/javascript"> var strCurrency = new Array(6); strCurrency[0]="Pound"; strCurrency[1]="Marc"; strCurrency[2]="Franc"; strCurrency[3]="Dollar"; strCurrency[4]="Nordic"; strCurrency[5]="Fivesmon"; var dblExchangeRate = new Array(6); dblExchangeRate[0]="1"; dblExchangeRate[1]="74"; dblExchangeRate[2]="8.54"; dblExchangeRate[3]="6.25"; dblExchangeRate[4]="98.1"; dblExchangeRate[5]="1.32"; function convertNumbers { } </SCRIPT> I want to see what the function would look like to be able to convert into different currencies by using arrays. I know that this would be a useless way to do it as they are updated every day, but it's for personal education purposes. (Note: The website contained a textbox in which to enter the amount in pounds, a drop-down box allowing the user to select currency, a button to click to convert, and another text box showing amount of money after converting.) Any help is greatly appreciated. Hi, Want to add numbers using JS. Have 4 text boxes for user entry. Want either a label (preferred) or fifth text box to automatically sum those entries. Did following but not working. Any suggestions? <script language="javascript"> var addRange = function() { var NoHrsRangeComp = document.getElementById("NoHrsRangeComp"); var NoHrsRangeCred = document.getElementById("NoHrsRangeCred"); var NoHrsRangeOT = document.getElementById("NoHrsRangeOT"); var NoHrsRangeRC = document.getElementById("NoHrsRangeRC"); var RangeSum = document.getElementById("RangeSum"); var sum = 0; if (isNaN(parseFloat(NoHrsRangeComp.value))){ NoHrsRangeComp.value = ""; } if (isNaN(parseFloat(NoHrsRangeCred.value))){ NoHrsRangeCred.value = ""; } if (isNaN(parseFloat(NoHrsRangeOT.value))){ NoHrsRangeOT.value = ""; } if (isNaN(parseFloat(NoHrsRangeRC.value))){ NoHrsRangeRC.value = ""; } sum = parseFloat(NoHrsRangeComp.value) + parseFloat(NoHrsRangeCred.value) + parseFloat(NoHrsRangeOT.value) + parseFloat(NoHrsRangeRC.value); RangeSum.innerHTML = sum; } </script> Input as follows: <input style="width: 50px" type="text" name="NoHrsRangeComp" id="NoHrsRangeComp" onblur="addRange();"/> <input style="width: 50px" type="text" name="NoHrsRangeCred" id="NoHrsRangeCred" onblur="addRange();"/> <input style="width: 50px" type="text" name="NoHrsRangeOT" id="NoHrsRangeOT" onblur="addRange();"/> <input style="width: 50px" type="text" name="NoHrsRangeRC" id="NoHrsRangeRC" onblur="addRange();"/> <input style="width: 50px" type="text" name="RangeSum" id="RangeSum" onblur="addRange();"/> For above entry prefer - label makes it look more like usual addition and does not confuse users to want to make entry. <label id="RangeSum" onblur="addRange();" style="border-bottom:medium"></label> John Hello friend, I need a JS validation code for validating numbers such that,Empty space and characters(including + and -) shouldn't be allowed,there should be only one decimal point,spaces and characters between numbers also shouldn't be permitted. This textbook is complete garbage, there is nothing in this thing about this topic at all. Here is the question I am trying to do: "Suppose you have a sequence of numbers Where every number is the previous number plus 3 1, 4, 7, 10, 13, 16, 19, 22 Write a program to output the first 10 number s of the sequence. You must calculate the numbers, you cannot just hard-code them into an array." Its a question on a test study guide. Heres what I got so far: Code: <html> <head> <script type="text/javascript"> VarX = 1 i = 3 VarY = VarX + i count++ do varY while count < 10 </script> </head> <body> </body> </html> helow to all im new here? iwant to ask on how to display the sum of the 20 numbers i allready get the everage but i want to display the sum together of the everage this my code.. <html> <body> <script type = "text/javascript"> var numtotal = parseInt(prompt("How many numbers do you want to sum up?","")); var total = 0; for (var i=0; i<numtotal; i++) { var ans = parseFloat(prompt ("Enter a number", "")); if ((isNaN(ans)) || (ans == "")) { alert ("You must enter a number!! "); i -- ; } else {total = total + ans/numtotal}; } alert (total); // the total </script> </body> </html> any body help me please? I have trouble with summing variable zbroj, it is summed like it is string, and i dont have any idea why. Help please! Code: function zbrojibode() { var i=0; var zbroj=new Number(0); while((document.getElementById('bodtxt5'+i).value)){ if((document.getElementById('bodtxt5'+i).value!="") || (document.getElementById('bodtxt5'+i).value!="NaN")) zbroj+=parseFloat(document.getElementById('bodtxt5'+i).value).toFixed(2); i++; } document.getElementById('ukupno').value=zbroj; } 1st, Hi Coding forums! I'll get to the point, I'm a noob -.- I'm using greasemonkey for a certain website. Basically, I'm using gm to refresh the page after a certain time, I was however wondering, If I can set it to a random number between 2 specific times? The code I'm using atm is setTimeout(function() { document.location.reload(); } , 10000); I know I have to use math.random, well, I think I do. But I'm not sure how to do it between 2 certain times? So to summarise, I'm trying to refresh a page at any given random time between say 5-10 minutes. Any help is appreciated, thanks! Hello Everyone! How can I write a string in JavaScript that will accept any phone number. Thanks I looked around for a solution but could not find one. I am trying to find combinations of numbers that can add up to a total. The numbers available and the total are different each time. For example, I have an array that contains the following numbers: [16,12,8,6,4,2] I want to find the combinations that add up to 140, like this: 8x16,1x12 8x16,1x8,1x4 11x12,1x8 Notice I do not do: 8x16,2x6 8x16,3x4 This is because as a rule, only the first number can be used in multiple of more than one. All other number pairs can only be a 1x. Output string could be formatted like this in a single string containing all combinations: 8x16,1x12|8x16,1x8,1x4|11x12,1x8 I have the following code attached that gives me a prime number. I can't seem to put the logic behind having this code print from an alert the prime numbers from 1-100. Of course, this code is only giving me "the" prime number. I just don't know where to begin, or how to store each number. Array maybe?
Code: var finding_primes = function() { var number = 31, prime = true; for ( var i = 2; i < number; i++ ) { if ( number % i == 0 ) prime = false; } if (prime) { alert( number + " is prime."); } else { alert( number + " is not prime."); } } |