Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Location
    Texas
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Unhappy Why won't this script accept decimal point?

    This is my first attempt at a script. I want it to accept a number with decimal point, and it will not. I altered it already once and it accepted decimal points, but then it stopped calculating the result. Var 2 and Var 3 are the only fields that need to have decimal points possible. Also, is it possible to recode this so var 3 can be entered as a whole number? I want the person to enter a profit percentage, like 30 for 30 percent, but I could only figure it out by making it 0.3 Any help would be greatly appreciated.

    Code:
     <script type="text/javascript" language="Javascript">
    
    var v1 = 10;
    var v2 = 10;
    var v3 = 0.3;
    var v4 = 40;
    var answer = 1200;
    
    function calculate () {
    // The Calculation: change operator in this equation to change the calculation
    answer = v1 * v2 * v3 * v4;
    
    var elem;
    elem = document.getElementById("v1");
    elem.value = v1;
    elem = document.getElementById("v2");
    elem.value = v2;
    elem = document.getElementById("v3");
    elem.value = v3;
    elem = document.getElementById("v4");
    elem.value = v4;
    
    elem = document.getElementById("answer");
    elem.value = answer;
    }
    
    function setValue(elem) {
    var val = 0.0;
    if (elem.value != "") {
    val = parseFloat(elem.value);
    }
    else {
    val = 0.0;
    }
    switch (elem.id) {
    case "v1": v1 = val; break;
    case "v2": v2 = val; break;
    case "v3": v3 = val; break;
    case "v4": v4 = val; break;
    }
    calculate();
    }
    </script>
        <meta charset="utf-8">
        <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
        <meta name="created" content="Mon, 11 Feb 2013 17:31:53 GMT">
        <meta name="description" content="">
        <meta name="keywords" content="">
        <title>Calculator</title>
        
        <style type="text/css">
        <!--
        body {
          color:#000000;
          background-color:#FFFFFF;
        }
        a  { color:#0000FF; }
        a:visited { color:#800080; }
        a:hover { color:#008000; }
        a:active { color:#FF0000; }
        -->
        </style>
        <!--[if IE]>
        <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
      </head>
      <body onload="calculate();">
      <div>Number of Employees</div> <form><input type="text" id="v1" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Hourly Rate<br /><input type="text" id="v2" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Markup Percentage<br /><input type="text" id="v3" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Hours Per Week<br /><input type="text" id="v4" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">=</span><br />Your Weekly Profit<br /><input type="text" id="answer" readonly="" /></form>

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,899
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    I am sorry to say that there are many errors.

    You should not assign the same names/ids v1 etc. to HTML form elements and Javascript variables.

    And even if there were such unduplicated form elements, you keep over-writing the value of elem.

    If all you want to do is to multiply four fixed numbers together, then

    Code:
    var v1 = 10;
    var v2 = 10;
    var v3 = 0.3;
    var v4 = 40;
    var ans = v1 * v2 *v3 * v4;  // you must not assign the same name to an HTML element and a Javascript variable
    document.getElementById("answer").value = ans;
    If you are trying to perform calculations on numbers entered into fields by the user, then you have a great many problems, incluing validation of the inputs to ensure that they are numbers (within a sensible range). It is pointless to use onkeyup here. The calculation will only make sense if all four numbers have been entered. But you must rename or (re-id) your form fields so as to not duplicate the Javascript variables.

    Be aware that form field values are strings unless/until converted to numbers by one of several methods, Number() being recommended.

    Code:
    var val1= Number(document.getElementById("v1").value) || 0;  // || 0 traps NaN entries and changes them to 0.
    val1 = Math.floor(val1);  // (or Math.round) - make val1 integer 
    // val1 is the name of the Javascript variable.  v1 is the id of the form field.
    // Now check that val1 is within a sensible range, and (presumably) not negative.
    Finally, put newlines between each line of your HTML code. It makes it unreadable if you run them all together into one long line.

    onkeyup="javascript: setValue(this)"
    javascript is completely unnecessary - I have forgotten exactly why in the distant past it was required in some early browsers.

    Your style sheet is also purposeless. It specifies what are the default colors anyway. I would advise you not to try to bite off too much at one sitting - keep your early attempts simple and check them frequently to see if they run OK, then build on your work. Rather than Coffee Cup Editor I would recommend that you use plain old Notetab or Notepad++.

    "In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)
    Last edited by Philip M; 02-13-2013 at 05:59 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #3
    New to the CF scene
    Join Date
    Feb 2013
    Location
    Texas
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Thank you for the help

    As I mentioned, this is my first attempt at javascript, and I took the code from a sample. The reason if filled in the variables at the beginning was to serve as a sample set of values, which I wanted the user to adjust.

    Your explanation went over my head, as I am so new to javascript. Could you fix the code I submitted so it works properly and allows people to enter a decimal point on field 2 and a straight percentage value (like 30)?

    Your explanation makes sense, but modifying the code with your fixes is beyond me, it is so easy to make mistakes with this.

    I would be extrememly grateful if you could show me the whole solution.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,032
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    I think the short answer to your request should be "No."

    Your code doesn't even make any sense.

    Every time there is an onkeyup, you update the values in v1 through v4. And you store the parsed value back in the form element.

    And then you do that *ALL OVER AGAIN* when you call calculate( ).

    The code is at least 3 times more complicated and larger than it needs to be.

    It truly needs to be just rewritten from the ground up. Honest.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    New to the CF scene
    Join Date
    Feb 2013
    Location
    Texas
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Could you fix it for a fee?

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,032
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    Ummm...is this homework???

    It feels like it.

    If not, what will it be used for? Can you convince us?

    It would only take a few minutes to re-code it, so no charge if it's not homework.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,899
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    AlanP - You should be aware that it is not really in your best interests that others do your all or most homework for you. Many people would regard that as cheating. Furthermore your teacher may gain a false and exaggerated idea of your programming capabilities and so not offer you the support you need. Also, if you hand in other people's work which you do not completely understand, then you will start to fall behind and your difficulties will increase. This is especially so if "Your explanation went over my head". That means that you are very much out of your depth.

    To repeat:- I would advise you not to try to bite off too much at one sitting - keep your early attempts simple and check them frequently to see if they run OK, then build on your work. Rather than Coffee Cup Editor I would recommend that you use plain old Notetab or Notepad++.

    Hint: be aware that a large proportion of the code used with data which is entered by the user is validation of the inputs. Were it not for this the code would be little different from multiplying four fixed numbers. Again, be aware that form field values are strings unless/until converted to numbers by one of several methods, Number() being recommended. As it happens in this case (multiplication) automatic type conversion will apply - but do not rely on that!!! You still need to make the conversion for validation purposes.

    If you want the user to enter a percentage value as 30 rather than .3, all you have to do is divide by 100 to get .3, add 1 to get 1.3 and then multiply the base value (say 10) by that (to give 13). But of course you must check that the value entered by the user is indeed a number such as 30 and not .3 as otherwise the answer is silly. So, for example, check that the percentage figure is either zero or greater than 1, and if not require it to be entered again. Zero is OK in the multiplication because 0/100 = 0 + 1 = 1.00.

    To give you the flavour of how you could do this (but well beyond you at this stage):-

    Code:
    Enter the percentage <input type = "text" id = "percent" size = "3" onblur = "checkit()">
    
    <script type = "text/javascript">
    
    function checkit() {
    var val = Number(document.getElementById("percent").value) || 0;  // trap NaN entries by converting to 0
    document.getElementById("percent").value = val;  // write it back to the field
    if ((val < 1) && (val !=0)  || (val <0)) {  // not negative, not a decimal less than 1
    alert ("You must enter either 0 or a number 1 or greater");   // alerts are considered obsolete nowadays - you should use DOM methods to display the message
    document.getElementById("percent").value = "";  // clear the field;
    document.getElementById("percent").focus();  // and refocus on it
    return false;
    }
    }
    
    </script>
    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
    Last edited by Philip M; 02-14-2013 at 09:48 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    New to the CF scene
    Join Date
    Feb 2013
    Location
    Texas
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts
    No, it's not homework. I'm trying to help out a guy I built a website theme for. I don't do javascript calculators, so when he wanted one, I gave it a shot by looking up on javascript source. The solution I came up with does work, but only if you don't try and alter the hourly rate field, or put in a decimal point. So, I am just out of my element here, and I'm trying to give him a solution that will work.

    Ideally, it would be nice if the visitor was able to enter a percentage in the markup percentage field, and in the hourly rate, they could enter a number with decimal place, like 10.25 / hour 11.75, whatever.

    Like I said, this isn't homework, I'm just out of my element doing javascript calculators.
    Here is the page on the website I built for him where I put in the bad version I cam up with.
    http://ironmanconsultants.com/?page_id=412

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,032
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Calculator</title>
        
    <style type="text/css">
    .required { 
        font-weight: bold;
        color : red;
    }
    .info {
        width: 30pt;
    }
    </style>
    </head>
    <body>
    <div id="content">
    <form id="EmpForm">
        <label>Number of Employees:&nbsp;&nbsp;&nbsp;
            <input class="info" name="NumEmps" value="10" />&nbsp;
            <span class="required">*</span>
        </label><br />
        <label>Hourly Rate:&nbsp;&nbsp;&nbsp;$
            <input class="info" name="Hourly"  value="10"/>&nbsp;
            <span class="required">*</span>
        </label><br />
        <label>Markup Percentage:&nbsp;&nbsp;&nbsp;
            <input class="info" name="Markup" value="30"/>%&nbsp;
            <span class="required">*</span>
        </label><br />
        <label>Hours Per Week:&nbsp;&nbsp;&nbsp;
            <input class="info" name="Hours"  value="40" />
            <span class="required">*</span>
        </label><br />
        <br/>
        <label>Your Weekly Profit:&nbsp;&nbsp;&nbsp;$
            <input name="Profit" readonly="readonly" />
        </label><br />
    </form>
    </div>
    
    <script type="text/javascript">
    (
      function( )
      {
          var form = document.getElementById("EmpForm");
          var inps = form.getElementsByTagName("input");
          for ( var i = 0; i < inps.length; ++i )    
          {
              if ( inps[i].className == "info" )
              {
                  inps[i].onchange = recalculate;
              }
          }
    
          function recalculate( )
          {
              var allOK = true;
              var result = 1;
              for ( var i = 0; i < inps.length; ++i )    
              {
                  if ( inps[i].className == "info" )
                  {
                      var inp = inps[i];
                      var val = inp.value.replace(/\s/g,"");
                      if ( val === "" || isNaN(val) )
                      {
                          allOK = false;
                      } else {
                          val = Number(val);
                          if ( inp.name == "Markup" ) { val = val * 0.01; }
                          result *= val;
                      }
                  }
              }
              form.Profit.value = ( allOK ? result.toFixed(2) : "n/a" );
          }
          recalculate( );
      }
    )();
    </script>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    AlanP (02-15-2013)

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,899
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Quote Originally Posted by AlanP View Post
    calculators.
    Here is the page on the website I built for him where I put in the bad version I cam up with.
    http://ironmanconsultants.com/?page_id=412
    Sorry, I find it impossible to believe that you wrote that web-page.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,032
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    I dunno, Philip. The <iframe> with the calculator in it is 100% a clone of the code he showed here in the forum.

    There's really not JavaScript in the rest of the site that isn't just some library pulled from somewhere. So it's not like he had to understand anything but HTML and CSS to get this far.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #12
    New to the CF scene
    Join Date
    Feb 2013
    Location
    Texas
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I don't know how things work where you come from, but where I come from, it is considered rude to call someone a liar. I'm not in the habit of lying to people, nor was I in any way trying to pretend javascript was something I am well versed in.

    Website design, graphics, page content and flow, and getting customers to buy whatever is is someone is trying to sell is what I do, and I do it quite well thank you very much.

    What I don't do is insult perfect strangers who ask for help from me, especially when that person has not attempted to insult me.

    Thank you for your help at any rate.

  • #13
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,899
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Fair enough, if you say so. It seemed to me a very big contast between the expert coding of that page and the seemingly juvenile code offered in Post#1. It gave the impression of school homework to me (and to Old Pedant as well). Perhaps web site design competence does not include any knowledge of Javascript. I withdraw my comment.
    Last edited by Philip M; 02-16-2013 at 04:27 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,032
    Thanks
    75
    Thanked 4,325 Times in 4,291 Posts
    Quote Originally Posted by Philip M View Post
    Perhaps web site design competence does not include any knowledge of Javascript.
    It's not common in my experience to find web site designers without competence in JavaScript, but it does happen. The primary designer with the company I am primarily contracting to is a bit more competent than AlanP, from the evidence of this thread, but not very much more. If he didn't have tons of jQuery libraries to fall back on, he'd be pretty much lost. (The mildly funny part is that his assistant is much much more competent, but without the design skills, and the boss wants the designs done right, so...)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,593
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Old Pedant View Post
    It's not common in my experience to find web site designers without competence in JavaScript, but it does happen.
    One good example would be Google - from the look of the so called JavaScript they provide they don't employ any web site designers who are competent with JavaScript.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •