我的HTML旁边有一个文本框和一个按钮。
我想要发生的是用户从下拉列表中选择一些内容。然后他们在框中输入一个数字。当他们单击“保存”时,它将获取该数字,并将其分配给JSON对象中的协调位置,以用于从下拉列表中选择的项目。
这是我迄今为止所拥有的一种。注释掉的线是我想在那个地方发生的事情。不知道如何编码。
https://jsfiddle.net/tq4xL0xs/
var userIngredients = {
Acorn:0,
Apple:0,
Armoranth:0,
BigHeartyRaddish:0};
function setUserAmountToVariables()
{
var tempNumber = document.getElementById("itemInput").value;
var tempItem = document.getElementById("dimeADozen");
//set tempnumber to whatever the user selected as the item from the dropdown (in useringredients object)
}

<select id="dimeADozen">
<option data-value="userIngredients.Acorn">Acorn</option>
<option value=userIngredients.Apple>Apple</option>
<option value=userIngredients.Armoranth>Armoranth</option>
<option value=userIngredients.BigHeartyRaddish>Big Hearty Raddish</option>
</select>
<input type="number" id="itemInput" min="0" max="99999">
<button onclick="setUserAmountToVariables();">Save Ingredient</button>
&#13;
答案 0 :(得分:0)
你应该使用
Object.assign(UserIngredient,{Nameofitem:tempNumber})
用对象
答案 1 :(得分:0)
首先,您需要将第一个选项的data-value
更改为value
。因为我们需要通过.value
检索所选的选项。
var userIngredients = {
Acorn:0,
Apple:0,
Armoranth:0,
BigHeartyRaddish:0};
function setUserAmountToVariables()
{
var tempNumber = document.getElementById("itemInput").value;
var tempItem = document.getElementById("dimeADozen").value;
tempItem = tempItem.split(".")[1];
userIngredients[tempItem] = tempNumber;
console.log(userIngredients);
}
&#13;
<select id="dimeADozen">
<option value="userIngredients.Acorn">Acorn</option>
<option value=userIngredients.Apple>Apple</option>
<option value=userIngredients.Armoranth>Armoranth</option>
<option value=userIngredients.BigHeartyRaddish>Big Hearty Raddish</option>
</select>
<input type="number" id="itemInput" min="0" max="99999">
<button onclick="setUserAmountToVariables();">Save Ingredient</button>
&#13;
答案 2 :(得分:0)
不要使用userIngredients.Acorn
作为选项中的值,而只需使用JSON对象的键就像Acorn
一样就足够了。
var userIngredients = {
Acorn:0,
Apple:0,
Armoranth:0,
BigHeartyRaddish:0};
function setUserAmountToVariables()
{
var tempNumber = document.getElementById("itemInput").value;
var tempItem = document.getElementById("dimeADozen").value;
userIngredients[tempItem] = tempNumber;
console.log(userIngredients);
}
<select id="dimeADozen">
<option value="Acorn">Acorn</option>
<option value="Apple">Apple</option>
<option value="Armoranth">Armoranth</option>
<option value="BigHeartyRaddish">Big Hearty Raddish</option>
</select>
<input type="number" id="itemInput" min="0" max="99999">
<button onclick="setUserAmountToVariables();">Save Ingredient</button>