根据同一HTML表单中的另一个下拉列表填充一个下拉列表

时间:2018-11-21 10:30:12

标签: javascript html list dropdown

我有一个HTML表单,其中包含许多选项,我想根据以前的用户选择来更改这些选项中的值: 假设我有这样的东西:

<select name="fruit">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="peach">Peach</option>
</select>

根据用户在此处选择的内容,在此显示不同值之后,我想要另一个下拉列表。如果用户在第一个下拉列表中选择“ Apple”,则将发生以下情况:

<select name="price">
    <option value="3">Apple 1kg 3€</option>
    <option value="5">Apple 2kg 5€</option>
    <option value="7">Apple 3kg 7€</option>
</select>

如果他选择“香蕉”,会发生以下情况:

<select name="price">
    <option value="4">Banana 1kg 4€</option>
    <option value="7">Banana 2kg 7€</option>
    <option value="10">Banana 3kg 10€</option>
</select>

值和文本需要根据第一个下拉列表进行更改,因为香蕉的价格与苹果的价格不同,依此类推。我读了一些有关它的主题,但我真的无法理解实现此目标所需的条件。在此之前以及从这里我所读到的内容中,我从未接触过ajax:Changing value of droplist based on the value of another dropdown list我需要一些基本的知识。仅使用JavaScript就能做到吗?

4 个答案:

答案 0 :(得分:1)

您可以使用一个对象保存值以及相关的下拉列表描述来实现。为此,您首先需要在下拉菜单中添加!a,以便在您选择新水果时它会检测到变化。使用此事件侦听器,您可以检索使用eventListener选择的选项的值。

使用选定的选项中的this.value,您可以继续从名为value的对象获取其关联的下拉值(这将返回一个数组)。获得此数组后,就可以遍历它并使用prices“构建” HTML字符串作为.reduce() select标记的选项。构建完此字符串后,您可以使用price将其附加到select标记内,它将HTML字符串“转换”为DOM对象(实际元素,而不仅仅是文本):

.innerHTML
let prices = {"apple":[{value:3,desc:"Apple 1kg 3&euro;"},{value:5,desc:"Apple 2kg 5&euro;"},{value:7,desc:"Apple 3kg 7&euro;"}],
             "banana":[{value:3,desc:"Banana 2kg 3.5&euro;"},{value:5,desc:"Banana 4kg 7&euro;"},{value:7,desc:"Banana 5kg 11&euro;"}],
             "peach":[{value:3,desc:"Peach 1.5kg 3&euro;"},{value:5,desc:"Peach 3kg 6&euro;"},{value:7,desc:"Peach 4kg 7&euro;"}]}

document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
  document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});

如果您不习惯使用<select name="fruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="peach">Peach</option> </select> <br /> <select name="price"> <option value="3">Apple 1kg 3€</option> <option value="5">Apple 2kg 5€</option> <option value="7">Apple 3kg 7€</option> </select>,可以改用常规的for循环:

.reduce()

答案 1 :(得分:0)

这是使用JQuery的元素创建和onchange事件的附加解决方案

// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}

// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
  // Clearing the price selector and getting the selected fruit
  $('#price-selector').empty()
  chosenFruit = this.value;
  
  // For each price in the fruitPrices for this fruit
  for (fruitIndex in fruitPrices[chosenFruit]) {
      // Get the price and create an option element for it
      price = fruitPrices[chosenFruit][fruitIndex];
      price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
      // Add the option to the price selector
      $('#price-selector').append(price_option)
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="peach">Peach</option>
</select>

<select id='price-selector' name="price">

</select>

答案 2 :(得分:0)

console.clear();

(function() {

  var fruitsField = document.querySelector('[name=fruits]')
  var amountField = document.querySelector('[name=amount]')
  var json = {};


  onReady(loadJson);
  fruitsField.addEventListener('change', populateAmount)


  function onReady(callback) {
    if (
      document.readyState === "complete" ||
      (document.readyState !== "loading" && !document.documentElement.doScroll)
    ) {
      callback();
    } else {
      document.addEventListener("DOMContentLoaded", callback);
    }  
  }

  function getSelectedFruit() {
    return fruitsField.value;
  }

  function populateFruits() {
    clearOptions(fruitsField)
    fruits = json.fruits
    for (var i in fruits) {
      addOption(fruitsField, i, fruits[i])
    }
  }

  function populateAmount() {
    clearOptions(amountField)
    var fruit = getSelectedFruit()
    fruits = json.fruits
    prices = json.prices[fruit]
    for (var i in prices) {
      addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
    }
  }

  
  // Load a json resource and start the fruit process
  function loadJson() {
    fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
    .then(function(response) {
      return response.json()
    })
    .then(function(response) {
      json = response
      populateFruits()
    })
    .catch(function(err) {
      console.error(err);
    })
  }


  // function loadJson() {
  //   var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
  //   json = JSON.parse(j)
  //   populateFruits()
  // }

  function addOption(select, value, text) {
    var option = document.createElement('option')
    option.setAttribute('value', value)
    option.textContent = text
    select.appendChild(option)
  }

  function clearOptions(select) {
    var children = select.children
    var childrenToRemove = [];
    for (var i = 1; i < children.length; i++) {
      childrenToRemove.push(children[i])
    }
    for (var i = 0; i < childrenToRemove.length; i++) {
      select.removeChild(childrenToRemove[i])
    }
  }

}())
<form>
  <select name="fruits" size="4">
    <option value="0">Select Fruit</option>
  </select>
  <select name="amount" size="4">
    <option value="0" >Select Amount</option>
  </select>
</form>

答案 3 :(得分:0)

<label>Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>

<div class="result"></div>

const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});