Показать \ скрыть параметры поля выбора на основе значения текстового поля - PullRequest
0 голосов
/ 03 июня 2019

Я создаю онлайн-форму, и у меня есть одно текстовое (числовое) поле и один выпадающий список с несколькими опциями.Мне нужно показать некоторые из этих опций, когда значение для текстового поля ниже нуля, и другие опции, когда значение текстового поля больше 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 ]

1 голос
/ 03 июня 2019

Используя vanilla 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>
0 голосов
/ 03 июня 2019

Тогда вы можете указать свои параметры, потому что использование значений в качестве идентификаторов может быть проблематичным.Также рекомендуем использовать слушатель для ввода в текстовое поле, вот пример, который я дал опциям с идентификатором "option1":

$('#text').on('input', function(){
  if($('#text').val() > 0){
    $('#option1').show();
  }
  else($('#option1').hide());
})
...