Just starting to use JavaScript Classes and have a quick question. In the example below, I want to ensure/convert certain properties to be numeric when I create the class. For instance, if the user enters "$10.50" for the unit price, I want the class to only have 10.50 so the total function works. I'm sure this can be done with a getter/setter but I can't quite figure out how to implement it.
<form name="orderform">
order date: <input name="order_date" value="" type=text>
<br>item_name: <input name="item_name" value="" type=text>
<br>unit_price: <input name="unit_price" value="" type=text>
<br>quantity: <input name="quantity" value="0" type=text>
</form>
class OrderItem {
constructor(
order_date,
item_name,
unit_price,
quantity,
) {
this.order_date = order_date;
this.item_name = item_name;
this.unit_price = unit_price;
this.quantity = quantity;
}
get total() {
return this.unit_price * this.quantity;
}
}
const orderitem1 = new OrderItem();
function GetNumber(val)
{
if (typeof val !== 'undefined')
{
return Number(val.replace(/[^0-9.-]+/g, ""));
}
else
{
return 0;
}
}
function getOrder()
{
$("#orderform").serializeArray().map(function(x){orderitem1[x.name] = x.value;});
var total = orderitem.total; //doesn't work if they enter '$10.50'
//...do stuff here with the orderitem1 class....
}
this.unit_price = GetNumber(unit_price), etc. in the constructor?