Не разрешать выбирать в сумме более n jQuery - PullRequest
0 голосов
/ 21 июня 2020

Я хотел бы создать функцию, в которой пользователь не должен иметь возможность выбирать значение, превышающее «n», из нескольких вариантов выбора. В моем случае я хочу ограничить пользователя выбором значения не более 4.

HTML:

<ul class="numberOfElementsList">
   <li>0</li>
   <li class="active">1</li>
   <li>2</li>
   <li>3</li>
</ul>
<select>
<ul class="numberOfElementsList">
   <li>0</li>
   <li class="active">1</li>
   <li>2</li>
   <li>3</li>
</ul>
<ul class="numberOfElementsList">
   <li>0</li>
   <li class="active">1</li>
   <li>2</li>
   <li>3</li>
</ul>

jQuery:

if(numBer > 4) {
        alert('You can not select more then 4.');
      } else if(numBer == 4) {
        $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li.active').nextAll('li').hide();
        $(this).nextAll('li').hide();
        $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li.active').nextAll('li').hide();
      } else if(numBer == 3) {
        if (indexNum == 3){
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(2)').nextAll('li').hide();
            $(this).nextAll('li.active').nextAll('li').hide();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li::nth-child(2)').nextAll('li').hide();
        } else {
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li.active, li:last-child').nextAll('li').hide();
            $(this).nextAll('li.active').nextAll('li').hide();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li.active, li:last-child').nextAll('li').hide();
            
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(3)').prevAll('li').show();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li:nth-child(3)').prevAll('li').show();
        }
      } else if(numBer == 2) {
        if (indexNum == 2){
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(3)').nextAll('li').hide();
            $(this).closest('.breedOptionsWrapper').find('li:last-child').hide();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li:nth-child(3)').nextAll('li').hide();
          
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(4)').prevAll('li').show();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li:nth-child(4)').prevAll('li').show();
        } else {
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(3)').nextAll('li').hide();
            $(this).closest('.breedOptionsWrapper').find('li:last-child').hide();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li:nth-child(3)').nextAll('li').hide();
          
            $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li:nth-child(4)').prevAll('li').show();
            $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li:nth-child(4)').prevAll('li').show();
        }
      } else {
        $(this).closest('.breedOptionsWrapper').nextAll('.breedOptionsWrapper').find('li').nextAll('li').show();
        $(this).prevAll('li').show();
        $(this).nextAll('li').show();
        $(this).closest('.breedOptionsWrapper').prevAll('.breedOptionsWrapper').find('li').nextAll('li').show();
      }

Здесь я хочу, чтобы пользователь ограничил максимум 4. Например, если пользователь выбирает комбинацию 1-2-1, 1-1-2, 3-1-0 или любую другую комбинацию, тогда другие значения параметров должны быть отключены. Я много чего пробовал, но не работал.

Спасибо

1 Ответ

1 голос
/ 21 июня 2020
  • Получите значение tot, используя .reduce()
  • L oop все элементы вашего параметра, и установите атрибуты hidden и disabled, если parseFloat(opt.value) > (maxTot - tot)

const $prod = $(".prod");
const $opts = $prod.find("option");
const maxTot = 4;   // Set here the desired total

$prod.on("change", function() {

  const tot = [...$prod].reduce((tot, sel) => {
    tot += parseFloat(sel.value);
    return tot;
  }, 0);
  
  $opts.each((i, opt) => {
    const is_hide = parseFloat(opt.value) > (maxTot - tot);
    opt.disabled = is_hide;
    opt.hidden = is_hide;
  });
 
});
<select class="prod">
  <option value="0">Product 0</option>
  <option value="1">Product 1</option>
  <option value="2">Product 2</option>
  <option value="3">Product 3</option>
</select>
<select class="prod">
  <option value="0">Product 0</option>
  <option value="1">Product 1</option>
  <option value="2">Product 2</option>
  <option value="3">Product 3</option>
</select>
<select class="prod">
  <option value="0">Product 0</option>
  <option value="1">Product 1</option>
  <option value="2">Product 2</option>
  <option value="3">Product 3</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...