skip to Main Content

I have two products, if I select ProductA I want the "Add" button to hide, but if I choose ProductB I want both buttons to show again.

How do I achieve that?

<input id="option1" value="ProductA" name="radio-group" type="radio">
<label for="option1" class="radio-custom-label">ProductA</label>
<input id="option2" value="ProductB" name="radio-group" type="radio">
<label for="option2" class="radio-custom-label">ProductB</label>

<button id="add">ADD</button>
<button id="buy">BUY</button>

<script>
    const value = document.querySelector('input[name="radio-group"]:checked').value;
    
    if(value === 'ProductA'){
        document.getElementById('add').style.display = 'none';
    }else{
        document.getElementById('add').style.display = 'block';
    }
</script>

2

Answers


  1. <input id="option1" value="ProductA" name="radio-group" type="radio">
    <label for="option1" class="radio-custom-label">ProductA</label>
    <input id="option2" value="ProductB" name="radio-group" type="radio">
    <label for="option2" class="radio-custom-label">ProductB</label>
    
    <button id="add">ADD</button>
    <button id="buy">BUY</button>
    
    <script>
        const addBtn = document.getElementById('add');
        const radioBtns = document.querySelectorAll('input[name="radio-group"]');
    
        for (const btn of radioBtns) {
          btn.addEventListener('change', (event) => {
            const value = event.target.value;
            if (value === 'ProductA') {
              addBtn.style.display = 'none';
            } else {
              addBtn.style.display = 'block';
            }
          });
        }
    </script>

    If I understood correctly, see if this is what you want

    Login or Signup to reply.
  2. you can simply use some CSS…

    #option1:checked ~ button#add { display : none }
    <input id="option1" value="ProductA" name="radio-group" type="radio">
    <label for="option1" class="radio-custom-label">ProductA</label>
    <input id="option2" value="ProductB" name="radio-group" type="radio">
    <label for="option2" class="radio-custom-label">ProductB</label>
    
    <button id="add">ADD</button>
    <button id="buy">BUY</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search