Ruijie Lu
Ruijie Lu

Reputation: 15

How to use a JavaScript variable in HTML file?

I want to print the value that the variable quantity holds in HTML

Here's my JavaScript code

class Ingredient {
  constructor (name, dateBought, expiryDate, quantity, expired){
    this.name = name;
    this.dateBought = dateBought;
    this.expiryDate = expiryDate;
    this.quantity = quantity;
    this.expired = false;
  }
  isExpired(){
    this.expired = true;
  }
  needReorder(){
    console.log(this. name + "need to be reordered")
  }
}

let cabbage = ("cabbage", new Date(2003,3,2), 23)

I'm trying to display the quantity in an HTML file like this, so far nothing prints

<script src="inventory.js"> 
  
  var quantity = cabbage.quantity
  
</script>
<script>
    document.write(quantity)
</script>

I know that there isn't anything wrong with my HTML because this code works perfectly fine

<script>
   document.write("write something")
</script>

Thank you in advance :)

Upvotes: 0

Views: 333

Answers (2)

wangdev87
wangdev87

Reputation: 8751

  1. You should use the variable cabbage.quantity in another script, not in the importing script.
<script src="inventory.js">   
</script>

<script>
    var quantity = cabbage.quantity
    document.write(quantity)
</script>
  1. Missing the new Ingredient with 4th argument.
let cabbage = new Ingredient("cabbage", new Date(2003,3,2), 23, 50)

Upvotes: 1

Heri Hehe Setiawan
Heri Hehe Setiawan

Reputation: 1633

You need to access the Ingredient class correctly. In your class declaration, quantity is expected to be the 4th argument, so you should pass that as follows:

new Ingredient("cabbage", new Date(2003,3,2), 23, 10)

Complete code:

class Ingredient {
  constructor (name, dateBought, expiryDate, quantity, expired){
    this.name = name;
    this.dateBought = dateBought;
    this.expiryDate = expiryDate;
    this.quantity = quantity;
    this.expired = false;
  }
  isExpired(){
    this.expired = true;
  }
  needReorder(){
    console.log(this. name + "need to be reordered")
  }
}

let cabbage = new Ingredient("cabbage", new Date(2003,3,2), 23, 10)
document.write(cabbage.quantity)

Upvotes: 1

Related Questions