I'm familiar with JavaScript, but not familiar with using it in the DOM. I'm trying to make a form that will accept an item name + properties and store it like I'm writing out the object below:
var grocery_list = {
"Banana": { category: "produce", price: 5.99 },
"Chocolate": { category: "candy", price: 2.75 },
"Wheat Bread": { category: "grains and breads", price: 2.99 }
}
Here is the sample HTML Form I have:
<form>
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="do stuff">
</form>
How can I use JavaScript take the input above and push it to an Object (like above)?
Add a listener to the form, collect the values, build an object and add it to the grocery_list, e.g.
<script>
var grocery_list = {}
function addGroceryItem(form) {
grocery_list[form.item.value] = {category: form.category.value, price: form.price.value};
return false;
}
</script>
<form onsubmit="return addGroceryItem(this)">
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="Add item">
<input type="button" value="Show list" onclick="console.log(grocery_list)">
</form>
Though I'd be tempted to use a plain button, not a submit button, and put the listener on the button's onclick handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With