亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據文本字段值顯示\隱藏選擇字段選項

根據文本字段值顯示\隱藏選擇字段選項

瀟瀟雨雨 2021-06-12 16:08:43
我正在創建在線表單,在表單中,我有一個文本(數字)字段和一個包含多個選項的下拉列表。當文本字段的值低于零時,我需要顯示其中一些選項,而當文本字段的值大于 0 時,我需要顯示其他選項。有人知道如何使用 JS 做到這一點嗎?(后端沒有數據庫)。謝謝你的幫助!我只能使用 js (jquery) + css 來完成這項任務。例子:<form id="test" name="test" target="_self">    <input id="text" name="text field" type="text">    <select id="list" name="list" size="1">        <option value="1">1</option>        <option value="2">2</option>        <option value="3">3</option>        <option value="4">4</option>    </select></form>
查看完整描述

2 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

使用香草JavaScript,您可以用模板沿data-*和重建選擇框通過測試,顯示一定的值data-*與輸入值的值。


const input = document.querySelector('#text')

const select = document.querySelector('#list')

const template = document.querySelector('template')


input.addEventListener('input', e => {

  let val = parseInt(e.target.value)

  // Clone the template

  let t = document.importNode(template.content, true)

  // Create a fragment for the new list

  let f = document.createDocumentFragment()

  

  for (var i = 0; i < t.children.length; i++) {

    let child = t.children[i]

    

    let show = parseInt(child.getAttribute('data-show') || '0')

    // If the data-show is larger than zero and in the input is larger than zero

    // Clone the current option and place it in the fragment

    if(show > 0 && val > 0) f.appendChild(child.cloneNode(true))

    

    // If the data-show is smaller than zero and in the input is smaller than zero

    // Clone the current option and place it in the fragment

    if(show < 0 && val < 0) f.appendChild(child.cloneNode(true))

  }

  

  // If the fragment doesn't have any options display a message

  if (f.children.length == 0) {

    let option = document.createElement('option')

    option.textContent = 'Enter a number in the text field'

    f.appendChild(option)

  }

  

  // Set the value of the select

  select.innerHTML = ''

  select.appendChild(f)

})

<form id="test" name="test" target="_self">

  <input id="text" name="text field" type="text">

  <select id="list" name="list" size="1">

    <option>Enter a number in the text field</option>

  </select>

</form>


<template>

  <option data-show="-1" value="1">1</option>

  <option data-show="-1" value="2">2</option>

  <option data-show="1" value="3">3</option>

  <option data-show="1" value="4">4</option>

  <!-- This value should never show since it is set to zero -->

  <option data-show="0" value="5">5</option>

  <!-- This value should never show since it doesn't have a data-show attribute -->

  <option value="6">6</option>

</template>


查看完整回答
反對 回復 2021-06-18
  • 2 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號