-3

I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.

<!DOCTYPE HTML>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <title>discount amount</title>
  </head>
  <body>
    <script>
     /* Input: purchase amount
      * Processing: determine through if statements if they get a discount
      * Output: final price after tax
      */
      // Computes and returns a discounted purchase amount.
      function getDiscountedAmount(purchase) {
        var purchase =
          parseInt(document.getElementById('purchase').value);
        var dayOfWeek = new Date().getDay();
        var output = document.querySelector("#output");

        let rate;
        if (purchase < 50) {
          rate = 0.06;
        } else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
          rate = 0.06;
        } else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
          rate = 0.06;
        }

        let discount = purchase * rate;
        return purchase - discount;
        output.innerHTML = "$" + String(getDiscountedAmount(200));
      }
    </script>
    Please enter your final price: <input type="text" id="purchase" size="5">
    <br>
    <button type="button" onclick="getDiscountedAmount(purchase)">discount?
    </button>
    <div id="output"></div>
  </body>
</html>
Seth B
  • 1,014
  • 7
  • 21
Aventrix
  • 15
  • 3
  • 1
    Partially [duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+get+value+from+input) of [How do I get the value of text input field using JavaScript?](https://stackoverflow.com/q/11563638/4642212). Then you still need to display the result in the `
    `. Please consult a [DOM tutorial](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents). `dayOfWeek == (2,3)` does not make sense. See [Javascript: The prettiest way to compare one value against multiple values](https://stackoverflow.com/q/9121395/4642212).
    – Sebastian Simon Feb 15 '21 at 21:21
  • 1
    Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Feb 15 '21 at 21:23
  • `dayOfWeek ==(2,3)` doesn't do what you think it does. If you want to test multiple values, you need to write multiple tests. – Scott Marcus Feb 15 '21 at 21:23
  • `parseFloat()` requires at least one argument. – Seth B Feb 15 '21 at 21:35
  • 1
    There is no such element as: `` – Scott Marcus Feb 15 '21 at 21:37
  • Remove the last `{` near `` – Seth B Feb 15 '21 at 21:39
  • Change `var purchase = parseFloat()` to `var purchase = parseInt(document.getElementById('purchase').value);` – Seth B Feb 15 '21 at 21:41
  • @ScottMarcus probably supposed to be `
    ` lol
    – Seth B Feb 15 '21 at 21:43
  • thanks, Seth that's what i was missing I think I have it from here but you all definitely helped me a ton – Aventrix Feb 15 '21 at 21:45
  • 1
    @SethB Probably, but pointing out the error. Also, not a good idea to do the `document.getElementById()` inside of the function with a static element. Get the reference just once outside of the function and then keep using that every time the function executes. – Scott Marcus Feb 15 '21 at 22:19
  • @Aventrix, I fixed it up a bit in my answer. – Seth B Feb 15 '21 at 23:01

3 Answers3

2

The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function

var purchase = parseFloat();

Try:

purchase = parseFloat(purchase);

so that it uses your input parameter.

Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)

And lastly your function returns a value but then you don't see that value anywhere, try using

console.log(getDiscountedAmount(200)) or whatever your price is

In terms of your input and output you want to use DOM manipulation to get the input and show the output.

If you want to see the value in your "output" then

var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));

Would be a simple DOM mechanism, but it's not the cleanest

One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them

Altogether a cleaner version of your code:

<!DOCTYPE HTML>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <title>discount amount</title>
  </head>
  <body>
    Please enter your final price: <input type="text" id="myInput" size="5" /><br />
    <button type="button" id="myButton">discount?</button>
    <div id="myOutput"></div>
    <script>
      var myInput = document.querySelector("#myInput");
      var myOutput = document.querySelector("#myOutput");
      var myButton = document.querySelector("#myButton");
      myButton.onclick = function() {
        // Computes and returns a discounted purchase amount.
        var purchase = parseFloat(myInput.value);
        var dayOfWeek = new Date().getDay();
        var rate;
        if (purchase < 50) {
          rate = 0.06;
        } else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
          rate = 0.06;
        } else if (purchase < 1000) {
          rate = 0.025;
        } else {
          rate = 0.03;
        }
        let discount = purchase * rate;
        var finalPrice = purchase - discount;
        output.innerHTML = "$" + String(finalPrice);
      };
    </script>
  </body>
</html>

I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
  • oh crap i didnt even notice that, thanks! other than that I do realize that to many of you I am a very early beginner. what am I missing even with that? – Aventrix Feb 15 '21 at 21:23
  • _“I don't know if that works”_ — It’s the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). The comparison is equivalent to `dayOfWeek == 3`. The answer still doesn’t address the actual _output_ of the function and the `
    `. The function currently returns nowhere.
    – Sebastian Simon Feb 15 '21 at 21:26
  • Ok thank you for that, and yes I addressed the output further below – Da Mahdi03 Feb 15 '21 at 21:29
  • okay so i have updated the code based on what all yall told me and it works but I'm still not getting anything to show up? (by the way, this is super helpful) – Aventrix Feb 15 '21 at 21:38
  • I added a cleaner version of the entire file that should work – Da Mahdi03 Feb 15 '21 at 21:47
  • @DaMahdi03 Your answer is good, I had already started answering, so I posted mine anyway. +1 – Seth B Feb 15 '21 at 21:56
  • @Aventrix if this is the correct answer please mark it as so – Da Mahdi03 Feb 16 '21 at 05:16
0

Here is what you are looking for:

body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}@media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <title>discount amount</title>
  </head>
  <body>
    <div class='wrapper'>
      <div class='content'>
        <label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
        <button type="button" onclick="getDiscountedAmount()">See discount</button>
        <div class='output-container'>Total: <span id='output'>--</span></div>  
      </div>
    </div>
    <script>
      //Get the output element
      outputEl = document.getElementById("output");
      function getDiscountedAmount() {
        //Gets the value of your input
        var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
        var dayOfWeek = new Date().getDay();
        var rate;
        if (purchase < 50) {
          rate = 0.06;
        } else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
          rate = 0.06;
        } else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
          rate = 0.06;
        }
        else {
          rate = 0.03;
        }
        let discount = purchase * rate;
        let output = purchase - discount;
        
        //Checks if output is a number.
        if(isNaN(output)){
          output = 'Not a number!';
        } else{
          output = '$' + output;
        }
        //Puts the output inside of your "output" <div>
        outputEl.textContent = output;
      }
    </script>
  </body>
</html>
Seth B
  • 1,014
  • 7
  • 21
  • 1
    Instead of adding a `load` event handler, just move the whole script so that it is positioned just prior to the closing body tag and let the code run at that point (which will effectively be at `DOMContentLoaded`, instead of `load` and won't require an event registration. Also, don't use `.innerHTML` when the string doesn't contain any HTML, use `.textContent` instead. – Scott Marcus Feb 16 '21 at 12:56
  • @ScottMarcus I just left the script where he had it, but you're right, it should be at the bottom. – Seth B Feb 16 '21 at 14:38
0

When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.

In your first line of the function you are using parseFloat(); wrong:

var purchase = parseFloat();

Do:

var purchase = parseFloat(purchase);

Than you need to get your input number. getDiscountedAmount(purchase) in the onclick event doesn't work. You can use this:

var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float

In the end you have to do this to show the number in you output div:

let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;

Here is your code and how i fixed it:

<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
 * Processing: determine through if statements if they get a discount
 * Output: final price after tax
 */
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
    var purchase = document.getElementById("purchase").value; // get value from text field
    purchase = parseFloat(purchase); // convert to float
    var dayOfWeek = new Date().getDay();
    var rate;
    if (purchase < 50) {
        rate = 0.06;
    }
    else if (purchase < 100 && dayOfWeek ==(2,3)) {
        rate = 0.06;
    }
    else if (purchase < 1000) {
        rate = 0.025;
    }
    else {
        rate = 0.03;
    }
    let discount = purchase * rate;
    let output = purchase - discount;
    document.getElementById("output").innerText = output; // set discont into your output div
    return output;
}
</script>
</head>

<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>  
<button type="button" onclick="getDiscountedAmount()">discount?</button>  
<div id="output"></div>  
</body>
</html>

I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.

  • so for the day of week i wanted it to only give the discount on certain days. this particular assignment tells me I need it to be Tuesday and Wednesday. I.E. 2 and 3 at least I'm thinking that's how it works. – Aventrix Feb 15 '21 at 22:04