从下拉菜单中为选项分配值

时间:2018-12-03 00:10:51

标签: javascript html css

我正在制作收银机类型程序。通过输入字段并按“添加”按钮,我可以将项目添加到下拉列表中。现在,我要为下拉菜单中选择的项目提供一个值。例如,我将“ Apple”添加到列表中,从下拉菜单中选择它,在输入字段中输入价格,然后通过按按钮将输入字段中的内容分配给“ Apple”。这是我走了多远:

function addProduct() {

    var list = document.createElement("OPTION");
    var name = document.getElementById("productName");

    list.innerHTML = name.value;
    name.value = "";

    document.getElementById("dropDown").appendChild(list);
}
<p>Add new product</p>
<input type="text" id="productName" placeholder="product name here">
<input type="button" id="btnAdd" value="Add Product" onclick="addProduct()">

<div>
    <p>Select a product then add the price per unit</p>
    <select id="dropDown"></select>
    <input type="text" id="productPrice" placeholder="price">
    <input type="button" value="Add Price" id="btnPrice" onlick="">
</div>

2 个答案:

答案 0 :(得分:0)

创建一个脚本,该脚本将获取选中的选项,然后分配其值。您可以检查控制台以查看是否已成功分配该值。

function addProduct() {

    var list = document.createElement("OPTION");
    var name = document.getElementById("productName");

    list.innerHTML = name.value;
    name.value = "";

    document.getElementById("dropDown").appendChild(list);
}

function addPrice(){
  var price = document.getElementById('productPrice').value;
  var product = document.querySelector('option:checked');
  product.value = price;
  console.log("Name of Product: "+product.innerHTML+"\n"+"Price: "+ product.value);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p>Add new product</p>
    <input type="text" id="productName" placeholder="product name here">
    <input type="button" id="btnAdd" value="Add Product" onclick="addProduct()">
    
    <div>
      <p>Select a product then add the price per unit</p>
      <select id="dropDown"></select>
      <input type="text" id="productPrice" placeholder="price">
      <input type="button" value="Add Price" id="btnPrice" onclick="addPrice()">
    </div>
  </body>
</html>

答案 1 :(得分:0)

获取所选选项,然后分配给其value

function addProduct() {
  var list = document.createElement("OPTION");
  var name = document.getElementById("productName");
  list.innerHTML = name.value;
  name.value = "";
  document.getElementById("dropDown").appendChild(list);
}

function addPrice() {
  var name = document.getElementById("productName");
  var option = name.options[name.selectedIndex];
  var price = document.getElementById("productPrice").value;
  option.value = price;
}
<p>Add new product</p>
<input type="text" id="productName" placeholder="product name here">
<input type="button" id="btnAdd" value="Add Product" onclick="addProduct()">

<div>
  <p>Select a product then add the price per unit</p>
  <select id="dropDown"></select>
  <input type="text" id="productPrice" placeholder="price">
  <input type="button" value="Add Price" id="btnPrice" onlick="addPrice()">
</div>