3

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)?

3
  • You should use a submit listener that gets the values from the inputs, constructs the required object and adds it the the grocery_list. Then cancel submit. You could also use a plain button and put the listener on the button. Commented Dec 3, 2014 at 6:50
  • @RobG Would that be a JQuery thing? Commented Dec 3, 2014 at 6:54
  • No. You could use jQuery, but it doesn't add any value here. Commented Dec 3, 2014 at 7:00

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That "fiddle" isn't using my code. This code works in Safari and every browser to IE 6, maybe older (except for the console.log part of course).
I just popped it in my text editor/HTML file and can see it printing to console.log...thank you! When I move the script code from the HTML to a separate JS file that I'm linked to, I get grocery_list not defined. Any ideas why?
No idea, check that grocery_list is defined. I've actually tested it in IE 6 on Windows 2000 — aren't VMs wonderful. ;-)
It is defined in your script, but when I move that script out of the HTML Page and into a linked JS file it seems to errors in console saying that it's not defined :/
1

This could be easily done with jQuery:

var objects = [];
$('form').on('submit', function(e){
    var item = $('#item').val(), category = $('#category').val(), price = $('#price').val();
    objects.push({item:{'category':category, 'price':parseFloat(price)}});
    console.log(JSON.stringify(objects));
    e.preventDefault();
});

By listenting to a submit event on the form, populating the object and pushing it to an object array. about reading the values from DOM, see the $('#input_id').val() which takes these values.

Assuming you though about pure JS, this could also be done:

var objects = [];
var form = document.getElementById('form');
form.onsubmit = function(e){
    var item = document.getElementById('item').value, category =document.getElementById('category').value, price = document.getElementById('price').value;
    objects.push({item:{'category':category, 'price':parseFloat(price)}});
    console.log(JSON.stringify(objects));
    e.preventDefault();
}

http://jsfiddle.net/70fnct9c/

UPDATE as robg noted, storing the objects in an object instead of array could also be done easily:

var objects = {}
................
................
objects[item] = {'category':category, 'price':parseFloat(price)}

http://jsfiddle.net/70fnct9c/2/

3 Comments

Thank you. What are these three things doing :parseFloat(price); - console.log(JSON.stringify(objects)); - e.preventDefault();
parseFloat stands for casting string to float (I assumed that you do not want string as a price..) console.log is a debugging tool printing values to the console tool (read more about developer tools online), and lastly, JSON.stringify converts values into JSON (you do not have to use it in your case, I used it in order to show the output)
The OP stores the items in an object, not an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.