Несколько сценариев выбора кнопки

У меня есть несколько сценариев, если выбраны определенные кнопки. Как я могу повторно выбрать, нажав кнопку еще раз?

СЦЕНАРИИ (1) только обучение (2) выезжать только за пределы НКР (3) выезжать только из PH (4) обучение + выезд за пределы НКР (5) обучение + выезд PH

Вот мой код до сих пор

<button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType()" id = "training" 
 name = "training" value = "training">
    <i class = "fas fa-book fa-2x"></i>
    <p>Training or Seminar</p>
</button>
<button class = "btn  btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType()" 
 id = "outsideNcr" name = "outsideNcr" value = "outsideNcr">
   <i class = "fas fa-bus-alt fa-2x"></i>
   <p>Travel outside NCR</p>
</button>
<button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType()" id = "outsidePh" 
 name = "outsidePh" value = "outsidePh">
   <i class = "fas fa-plane-departure fa-2x"></i><br>
   <p>Travel outside PH</p>
</button>

<script>
  
  function selectReimbursementType(x) {
    var element = document.getElementById(x);
    var currentValue = document.getElementById(x).value;

    if (currentValue == 'training') {
      element.classList.add('is-active');
    } else if (currentValue == 'outsideNcr') {
      element.classList.add('is-active');
      document.getElementById('outsidePh').setAttribute('disabled', true);
    } else if (currentValue == 'outsidePh') {
      element.classList.add('is-active');
      document.getElementById('outsideNcr').setAttribute('disabled', true);
    }
  }
</script>

https://jsfiddle.net/oy0zh4ws/2/

Вам нужно такое поведение кнопки? - ibb.co/FzbJqHC

s.kuznetsov 21.12.2020 06:01

@sergeykuznetsov вроде. если выбор NCR для движения наружу не выбран, заблокированная кнопка должна быть включена.

Alyssa Reyes 21.12.2020 06:05
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
2
57
3
Перейти к ответу Данный вопрос помечен как решенный

Ответы 3

Ответ принят как подходящий

Я использовал методы toggle() и toggleAttribute().

Просто используйте этот js-код:

function selectReimbursementType(x) {
  var element = document.getElementById(x);
  var currentValue = document.getElementById(x).value;
  var ncr = document.getElementById('outsidePh');
  var ph = document.getElementById('outsideNcr');

  if (currentValue == 'training') {
    element.classList.toggle('is-active');
  } else if (currentValue == 'outsideNcr') {
    element.classList.toggle('is-active');
    ncr.toggleAttribute('disabled');
    
  } else if (currentValue == 'outsidePh') {
    element.classList.toggle('is-active');   
    ph.toggleAttribute('disabled');
  }
}

@AlyssaReyes, всегда рада помочь.

s.kuznetsov 21.12.2020 07:07
  1. Используйте element.classList.toggle для переключения класса.
  2. Отключите отключенное состояние элементов и установите снова в зависимости от условия.

Попробуйте ниже.

function selectReimbursementType(x) {
  var element = document.getElementById(x);
  var currentValue = document.getElementById(x).value;

  // toggle elements is-active class.
  element.classList.toggle('is-active');

  // reset disabled
  document.getElementById('outsideNcr').removeAttribute('disabled');
  document.getElementById('outsidePh').removeAttribute('disabled');

  // set disabled button
  if (currentValue == 'outsideNcr' && element.classList.contains('is-active')) {
    document.getElementById('outsidePh').setAttribute('disabled', true);
  }

  if (currentValue == 'outsidePh' && element.classList.contains('is-active')) {
    document.getElementById('outsideNcr').setAttribute('disabled', true);
  }

}
html {
  font-size: 14px;
  font-family: 'Nunito', sans-serif;
}

.reimbursement-buttons.preview-btn {
  margin-top: 20px;
  margin-bottom: 5px;
  margin-left: auto;
  margin-right: auto;
  color: #ffffff;
}

.footer {
  background: #7f7f7f;
  padding: 10px 0px;
}

.reimbursement-card p {
  font-size: 12px;
  margin-bottom: 0;
}

.reimbursement-card .btn.is-active {
  background: #32c5ff;
  color: #ffffff;
  content: "\f058";
}

.reimbursement-card .btn:hover {
  background: #32c5ff;
  color: #ffffff;
}

.reimbursement-card .btn:disabled:hover {
  background: none;
  color: #000000;
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<link rel = "stylesheet" type = "text/css" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

<div class = "d-flex justify-content-center form-row">
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('training')" id = "training" name = "training" value = "training">
          <i class = "fas fa-book fa-2x"></i>
          <p>Training or Seminar</p>
        </button>
      </div>
    </div>
  </div>
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn  btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('outsideNcr')" id = "outsideNcr" name = "outsideNcr" value = "outsideNcr">
          <i class = "fas fa-bus-alt fa-2x"></i>
          <p>Travel outside NCR</p>
        </button>
      </div>
    </div>
  </div>
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('outsidePh')" id = "outsidePh" name = "outsidePh" value = "outsidePh">
          <i class = "fas fa-plane-departure fa-2x"></i><br>
          <p>Travel outside PH</p>
        </button>
      </div>
    </div>
  </div>
</div>

Привет. Спасибо за ваш ответ. Отдать честь!

Alyssa Reyes 21.12.2020 07:05

Класс is-active имеет CSS, и при нажатии кнопки кнопка получает класс is-active. Поэтому, когда кнопка повторно нажимается, кнопка получает один и тот же класс дважды. Таким простым подходом является удаление класса is-active. Как вы предложили другое ниже:

СЦЕНАРИИ (1) только обучение (2) только выезд из NCR (3) выезд только из PH (4) обучение + выезд из NCR (5) обучение + выезд из PH

Эти СЦЕНАРИИ можно сбросить, удалив атрибут disabled.

function selectReimbursementType(x) {
  var element = document.getElementById(x);
  var currentValue = document.getElementById(x).value;

    function unSetOption() {
    element.classList.remove('is-active')
    document.getElementById('outsidePh').removeAttribute('disabled');  
    document.getElementById('outsideNcr').removeAttribute('disabled');      
  }
  
  if (element.classList.contains('is-active')) {
    unSetOption();
  } else if (currentValue == 'training') {    
    element.classList.add('is-active');
  } else if (currentValue == 'outsideNcr') {    
    element.classList.add('is-active');
    document.getElementById('outsidePh').setAttribute('disabled', true);
  } else if (currentValue == 'outsidePh') {       
    element.classList.add('is-active');
    document.getElementById('outsideNcr').setAttribute('disabled', true)    
  }
}
html {
        font-size: 14px;
        font-family: 'Nunito', sans-serif;
      }
      
      
      .reimbursement-buttons.preview-btn {
        margin-top: 20px;
        margin-bottom: 5px;
        margin-left: auto;
        margin-right: auto;
        color: #ffffff;
      }
      
      .footer {
        background: #7f7f7f;
        padding: 10px 0px;
      }

      .reimbursement-card p {
        font-size: 12px;
        margin-bottom: 0;
      }
            
      .reimbursement-card .btn.is-active {
        background: #32c5ff;
        color: #ffffff;
        content: "\f058";
      }

      .reimbursement-card .btn:hover {
        background: #32c5ff;
        color: #ffffff;
      }

      .reimbursement-card .btn:disabled:hover {
        background: none;
        color: #000000;
      }
<div class = "d-flex justify-content-center form-row">
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('training')" id = "training" name = "training" value = "training">
          <i class = "fas fa-book fa-2x"></i>
          <p>Training or Seminar</p>
        </button>
      </div>
    </div>
  </div>
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn  btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('outsideNcr')" id = "outsideNcr" name = "outsideNcr" value = "outsideNcr">
          <i class = "fas fa-bus-alt fa-2x"></i>
          <p>Travel outside NCR</p>
        </button>
      </div>
    </div>
  </div>
  <div class = "p-3">
    <div class = "card">
      <div class = "card-body d-flex flex-column align-items-start reimbursement-card p-0">
        <button class = "btn btn-block btn-lg py-3" type = "button" onclick = "selectReimbursementType('outsidePh')" id = "outsidePh" name = "outsidePh" value = "outsidePh">
          <i class = "fas fa-plane-departure fa-2x"></i><br>
          <p>Travel outside PH</p>
        </button>
      </div>
    </div>
  </div>
</div>

Другие вопросы по теме