JavaScript - Problem With Bigint.js , Not Performing Subtraction On Bigninteger Numbers
Hello,
I am using BigInt.js javascript package for performing arithmetic operations on biginteger numbers. Following are some of the interfaces provided by this plugin: // Interfaces: // x = new BigInt("1234567890123456789012345678901234567890"); // y = new BigInt("0x123456789abcdef0123456789abcdef0"); // z = x.clone(); // z = bigint_uminus(x); // z = bigint_plus(x, y); // z = bigint_minus(x, y); // z = bigint_mul(x, y); // z = bigint_div(x, y); // z = bigint_mod(x, y); // cmp = bigint_cmp(x, y); /* return -1, 0, or 1 */ // num = bigint_number(x); /* convert normal number (may be floating) */ // From the above interfaces , I just need to use bigint_plus and bigint_minus functions for my code. But bigint_minus is not returning the proper subtraction for two big integers. Attached is the BigInt.txt file , before using please rename the file to BigInt.js.apart from bigint_minus functions other functions are working fine for me. Please let me know what is the problem with bigint_minus() function. Thanks, Dinesh Similar TutorialsThis is a homework assignment I am trying to work on. Simple put my goal is to be able to click a "generate payslip" button and it should pop up "(firstname)(lastname), you will pay (var1*0.2) in federal taxes and (var2*0.1) in state taxes. Then i will add a reset button to the fields. I am NOT asking you to do this for me, i just need some help on what im doing wrong seeing as my teacher refuses to be of any help. Here is what i got.. dont laugh. After literally spending hours on the computer trying to find help codes I took out the bulk of trash i had in there because it never worked, but at one point i had something like this var1 = num1 var2 = num2 var3 = num3 var answer= num3*0.2 var answer2= num3*0.1 Then i tried to include that in my alert box and even tweaked it over and over and either completely eliminated the alert box itself or include all the text in my equation. Either way, if someone can enlighten me on how to properfly perform a calculation in an alert box i would be ecstatic. <HTML> <HEAD> <center><b> Here is a pay slip generator that will determine your net annual salary. Simply type in your first and last name along with gross salary and hit calculate. Doing this will let you know how much you will end up paying in both Federal and State taxes. </center></b> <form action="" method="post" name="GPS"> <p> Enter your First Name: <input name="num1" type="text" id="num1" size="10" maxlength="10"> </p> <p> Enter your Last Name: <input name="num2" type="text" id="num2" size="10" maxlength="10"> </p> <p> Enter your gross salary: <input name="num3" type="#" id="num3" size="10" maxlength="10"> </p> Click this button to calulate your annual net pay! <script type="text/javascript"> function calculate() { alert("You type something"); } </script> <input type="button" onclick="calculate()" value="Generate Pay Slip" /> </FORM> </body> </html> </script> Good day all: I have an editable invoice that I have added a sales tax option with a js function doMath(). Prior to my modification with the sales tax option all worked well. the invoice which code is the following: Code: <textarea id="address" rows="6" cols="38" disabled="true">Website: Email: TaxID: </textarea > <div id="vehicleid"><label><strong><u>Vehicle Information</u></strong></label><p>Year: <?php echo $edit_caryear?></p><p>Type: <?php echo $dhtmlgoodies_categoryupdate?></p><p>Make: <?php echo $dhtmlgoodies_subcategoryupdate?></p><p>ClientID# <?php echo $edit_clientID?></p><p>Current Mileage <?php echo $edit_mileage?></p></div> <!--</div>--> <!--<div id="logo"> <div id="logoctr"> <a href="javascript:;" id="change-logo" title="Change logo">Change Logo</a> <a href="javascript:;" id="save-logo" title="Save changes">Save</a> | <a href="javascript:;" id="delete-logo" title="Delete logo">Delete Logo</a> <a href="javascript:;" id="cancel-logo" title="Cancel changes">Cancel</a> </div> <div id="logohelp"> <input id="imageloc" type="text" size="50" value="" /><br /> (max width: 540px, max height: 100px) </div> <img id="image" src="images/logo.png" alt="logo" width="280" height="33" /> </div>--> </div> <div style="clear:both"></div> <br> <div id="customer"> <?php echo $edit_firstname ?> <?php echo $edit_lastname?><p><?php echo $edit_address?></p><p><?php echo $edit_city?>, <?php echo $edit_state?>, <?php echo $edit_zipcode?></p> </div> <div id=invoicehead> <table id="meta"> <tr> <td class="meta-head">Invoice #</td> <td><textarea style="background: transparent;" name="invoicenum" id="invoicenun" disabled="true"><?php srand(time()); $random = (rand()%1000000); print("$random"); ?></textarea></td> </tr> <tr> <td class="meta-head">Date</td> <td><textarea name="date" id="date">December 15, 2009</textarea></td> </tr> <tr> <td class="meta-head">Amount Due</td> <td><div name="due" class="due">$0.00</div></td> </tr> </table> </div> <table id="items"> <tr> <th>Item</th> <th>Description</th> <th>Unit Cost</th> <th>Quantity</th> <th>Price</th> </tr> <tr class="item-row"> <td class="item-name"><div class="delete-wpr"> <!--<label for=\"dhtmlgoodies_category\">Make:</label>--> <?php echo $edit_servicearea?><br> <!--<SELECT NAME="edit_servicearea"> <OPTION>Select One <OPTION>Air Intake <OPTION>Brake <OPTION>Clutch <OPTION>Cooling System <OPTION>Driveshaft & Axle <OPTION>Engine Mechanical <OPTION>Exhaust <OPTION>Steering <OPTION>Suspension <OPTION>Transmission <OPTION>Other </SELECT>--> <a class="delete" href="javascript:;" title="Remove row">X</a></div></td> <td class="description"> <textarea name="servicedesc" cols="255" rows="20"><?php echo str_replace('<br/>', "\n", "$inputbox");?></textarea></td> <td><textarea name="cost" class="cost">$0.00</textarea></td> <td><textarea name="qty" class="qty">1</textarea></td> <td><span name="price" class="price">$0.00</span></td> </tr> <tr class="item-row"> <td class="item-name"><div class="delete-wpr"> <textarea name="Labor rate" cols="20" rows="3">Labor</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td> <td class="description" wrap=virtual><textarea>Labor rate for the performance of work --excluding cost for parts.</textarea></td> <td><textarea class="cost">$75.00</textarea></td> <td><textarea class="qty" rows="2" cols="10">0</textarea></td> <td><span class="price">$0.00</span></td> </tr> <tr id="hiderow"> <td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td> </tr> <tr> <td colspan="2" class="blank"> </td> <td colspan="2" class="total-line">Subtotal</td> <td class="total-value"><div id="subtotal">$0.00</div></td> </tr> <tr> <td colspan="2" class="blank"> </td> <td colspan="2" class="tax-line" style="text-align: left" valign="top">INCLUDE TAX? <input type = "checkbox" id = "taxbox" onclick = "doMath()"><br>DC 5.576%</td> <td class="total-value"><textarea class="tax" id="tax" >$0.00</textarea></td> </tr> <tr> <td colspan="2" class="blank"> </td> <td colspan="2" class="total-line">Total</td> <td class="total-value"><div id="total">$0.00</div></td> </tr> <tr> <td colspan="2" class="blank"> </td> <td colspan="2" class="total-line">Amount Paid</td> <td class="total-value"><textarea id="paid">$0.00</textarea></td> </tr> <tr> <td colspan="2" class="blank"> </td> <td colspan="2" class="total-line balance">Balance Due</td> <td class="total-value balance"><div class="due">$0.00</div></td> </tr> </table> </div> <!--<div id="terms"> <h5>Terms</h5> <textarea>NET 30 Days. Finance Charge of 1.5% will be made on unpaid balances after 30 days.</textarea> </div>--> </div> <div> <SCRIPT LANGUAGE="JavaScript"> document.write('<form><input type=button value="Refresh" onClick="history.go()"></form>') </script> </div><br> <div id="option"> <input type="button" id="button" value="Return to Main Menu" onclick="window.location='/andy/addentry.php' " /> <input type="hidden" name="servicedesc" value="<?php echo $_POST['servicedesc']; ?>"> <br> <p> <! I added this button, so that it returns us to the main Menu.> <INPUT TYPE="button" onClick="window.print()" value="Print" /><br> </p> <p><! The above button Clears all the Field's contents ><input type="submit" name="submit" value="Save Changes"> </div> </form> the section of the code higlighted in red is where my problem arises. To achieve the desired results(at least so that I thought), I included the following fuction in my js fuction file which is as follows: Code: function update_total() { var total = 0; $('.price').each(function(i){ price = $(this).html().replace("$",""); if (!isNaN(price)) total += Number(price); }); total =roundNumber(total,2); $('#subtotal').html("$"+total); $('#total').html("$"+total); //$('#tax').html("$"+total); update_balance(); } var taxRate = .0575; function doMath(){ //var subtotal = 0.00;//$('.price').each(function(i); var subtotal = ('#subtotal');//.html("$"+total); if (document.getElementById("taxbox").checked) { tax = subtotal* taxRate; //DC 5.576% tax = roundNumber(tax,2);//the 2 represent the number of digits to round numbers to after decimal point //tx = " Incl. 5.576%"; } document.getElementById("tax").value = "$" +tax; } function update_balance() { var due = $("#total").html().replace("$","") - $("#paid").val().replace("$",""); due = roundNumber(due,2); $('.due').html("$"+due); } function update_price() { var row = $(this).parents('.item-row'); var price = row.find('.cost').val().replace("$","") * row.find('.qty').val(); price = roundNumber(price,2); isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price); update_total(); } function bind() { $(".cost").blur(update_price); $(".qty").blur(update_price); } $(document).ready(function() { $('input').click(function(){ $(this).select(); }); $("#paid").blur(update_balance); $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><SELECT NAME="edit_servicearea"><option>Select One<option>Air Intake<option>Brakes<option>Clutch<option>Cooling System<option>Driveshaft & Axle<option>Engine Mechanical<option>Exhaust<option>Steering<option>Suspension<option>Transmission<option>Other</select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea>Description</textarea></td><td><textarea class="cost">$0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">$0</span></td></tr>'); if ($(".delete").length > 0) $(".delete").show(); bind(); }); $(".tax").blur(update_total);//binding tax //bind(); bind(); $(".delete").live('click',function(){ $(this).parents('.item-row').remove(); update_total(); if ($(".delete").length < 2) $(".delete").hide(); }); $("#cancel-logo").click(function(){ $("#logo").removeClass('edit'); }); $("#delete-logo").click(function(){ $("#logo").remove(); }); $("#change-logo").click(function(){ $("#logo").addClass('edit'); $("#imageloc").val($("#image").attr('src')); $("#image").select(); }); $("#save-logo").click(function(){ $("#image").attr('src',$("#imageloc").val()); $("#logo").removeClass('edit'); }); $("#date").val(print_today()); }); Again, here my sales tax is highlighted in red. My problem specifically is that I'm unable to: 1.) get the sales tax rate to calculate based on the value of the subtotal, and 2.) on selection for including taxes, to bind the sale tax amount to the total. I trust someone can provide some guidance! Mossa 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; } Below is the script and form fields I am working with. What I want to do is sum the two textbox fields and have the result show in the total textbox. The code works fine and the total textbox is updated with the value of form1.basic. The problem occurs when I add the "+ parseInt(document.form2.supporter.value)" code in the script section. What am I doing wrong? Thank you for your time and help. Code: <script type="text/javascript"><!-- function updatesum() { document.frmtotal.total.value = parseInt(document.form1.basic.value) + parseInt(document.form2.supporter.value)} //--></script> <tr> <td width="111"><form id="form1" name="form1" method="post" action=""> <label for="basic">$</label> <input name="basic" type="text" id="basic" size="7" maxlength="7" onchange="updatesum(this.form)" /> </form></td> </tr> <tr> <td><form id="form2" name="supporter" method="post" action=""> <label for="supporter">$</label> <input name="supporter" type="text" id="supporter" size="7" maxlength="7" onchange="updatesum(this.form)" /> </form> Good day! I am new in javascript function. I have Javascript code for auto calculate here is the code: Code: <script type="text/javascript" language="javascript"> function autocalearn(oText) { if (isNaN(oText.value)) //filter input { alert('Numbers only!'); oText.value = ''; } var field, val, oForm = oText.form, TotEarn = a = 0; for (a; a < arguments.length; ++a) //loop through text elements { field = arguments[a]; val = parseFloat(field.value); //get value if (!isNaN(val)) //number? { TotEarn += val; //accumulate } } var tot=Number(TotEarn) + Number(document.getElementById('Amount').value); oForm.TotEarn.value = tot.toFixed(2); //oForm.TotEarn.value = TotEarn.toFixed(2); //out } </script> <!--Total Deduction AutoCompute--> <script type="text/javascript" language="javascript"> function autocalded(oText) { if (isNaN(oText.value)) //filter input { alert('Numbers only!'); oText.value = ''; } var field, val, oForm = oText.form, TotalDed = a = 0; for (a; a < arguments.length; ++a) //loop through text elements { field = arguments[a]; val = parseFloat(field.value); //get value if (!isNaN(val)) //number? { TotalDed += val; //accumulate } } //oForm.TotalDed.value = TotalDed.toFixed(2); //out var totded=Number(TotalDed) + Number(document.getElementById('Deductions').value); oForm.TotalDed.value = totded.toFixed(2); } </script> and now my problem is...I have a textbox for the overall total, and i want it automatic subtract the total earn and total deduction.. I will attach my codes for further understanding. Thank you in advance 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 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> 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. 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> 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, 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> 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? 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> 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 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. 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. 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. 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! Is 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! |