You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API获取下拉框选中项价格并显示在表单左下角

实现方案

你需要对现有代码做3处修改即可实现需求:

  • 给HTML中左下角显示价格的span添加唯一id,方便JS选中修改内容
  • 渲染下拉框option时,把对应价格存入选项的自定义属性中
  • 给下拉框绑定change事件,选中选项时读取对应价格更新到span标签

下拉框选值逻辑不要用click事件,改用change事件更合理,只有当选中的选项真正发生变化时才会触发,避免不必要的重复执行。

修改后的完整代码

HTML代码

<form class ="choose-form">
  <div class="mb-3">
    <select  class="form-select" id ="question">
      <option>Select a category : Love,carrer,more ...</option> 
    </select>
  </div>
  <nav class="navbar navbar-expand-lg navbar-light">   
    <!-- 给价格span加唯一id -->
    <span id="price-display"> ₹99(including GST)</span>
    <span>Ideas what to ask</span>
    <div class="profile-icon" style="justify-content-end">
      <button type="submit" class="btn btn-warning">Ask a Question </button>
    </div>
  </nav>
</form>

JS代码

const apiData =[
  {
      "id":"1",
      "question" :"Love",
      "price":"90"
  },
  {
      "id":2,
      "question":"Carrer",
      "price":"80"
  },
  {
      "id":"3",
      "question":"Shadi",
      "price":"100"
  },
  {
      "id":"4",
      "question":"Future",
      "price":"200"
  },
  {
      "id":"5",
      "question":"Office",
      "price":"300"
  },
  {
      "id":"6",
      "question":"After-Life",
      "price":"400"
  }
]


async function loadUsers() {
  //const response = await fetch("../reference_json/questions_API.js");
  //return response.json();
  return apiData
}

document.addEventListener("DOMContentLoaded", async () => {
  try {
    const users = await loadUsers();
    const selectContainer = document.getElementById('question');
    const priceSpan = document.getElementById('price-display');

    users.forEach(user => {
      const optionElem = document.createElement('option');
      optionElem.innerText = user.question;
      // 把价格存入option的自定义属性
      optionElem.dataset.price = user.price;
      selectContainer.appendChild(optionElem);
    });

    // 绑定下拉框change事件
    selectContainer.addEventListener('change', () => {
      const selectedOpt = selectContainer.options[selectContainer.selectedIndex];
      const price = selectedOpt.dataset.price;
      if (price) {
        priceSpan.innerText = `₹${price}(including GST)`;
      } else {
        // 选中默认提示项时恢复默认价格
        priceSpan.innerText = '₹99(including GST)';
      }
    })
  } catch (e) {
    console.log('ERROR');
    console.log(e);
  }
});

内容的提问来源于stack exchange,提问作者user14186487

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:12:00