I'm building a simple recipe app using Node/Express. User gets a 'new recipe' HTML form, where they can click an 'add ingredient' button and add as many ingredients to the form as they need. Using jQuery, every time the plus icon is clicked, a new text input for the new ingredient is generated:
var newIngredient = $('#newIngredient').val();
ingredientCount++;
//give each ingredient a unique name based on count
var ingredientID = "ingredient_" + ingredientCount
// reset input to blank
$("#newIngredient").val("");
// add ingredient to list for user to see or edit.
$("#ingredientsList").append(
'<input class="form-control" type="text" required
name=' + ingredientID + ' value="' + newIngredient + '">')
Each ingredient added is assigned a unique name via the counter. This all works fine and when the form is submitted I get:
{
name: 'Soup',
ingredient_1: 'carrots',
ingredient_2: 'salt',
ingredient_3: 'turnips',
method: 'Throw all these ingredients together and voila, you have a terrible soup.'
}
In the backend, I want to take each of these ingredients and add them to an 'ingredients' array (because I don't think I can send an array of ingredients from the HTML form). I obviously don't want to hard code ingredients.push(req.body.ingredient_1), ingredients.push(req.body.ingredient_2) etc... because the number of ingredients for each recipe will vary.
Is there a way to increment variable names? This might illustrate what I'm trying to do, though I know it obviously does not work:
ingredientsList=[];
var counter=1;
while(req.body.**"ingredient_"+counter**){
ingredientsList.push(req.body.**'ingredient_'+counter**);
counter++
}
Alternative ideas for passing dynamically created name:value pairs from an HTML form to JS backend would be welcome, but I would also like to know if it is possibly to dynamically increment parameters in the way I have tried above - req.body.parameter[i]
Thanks!