Search code examples
javascripthtmlformsradio-button

How to remove/hide the dynamic radio button by value in javascript


How to remove/hide the radio button by value using javascript and not jquery. I have three radio buttons which has dynamic ids and name. I would like to know how to remove the radio button by values

I got stuck not sure how to do in javascript, on page load

var option_value1= ["bank", "credit", "debit"]; //show all the three buttons
var option_value2= ["bank", "credit"] //show only bank and credit radio buttons.

<form>
 <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-bank transfer-${provider.id}" value="bank" checked>
  <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-credit-${provider.id}" value="credit">
  <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-debit-${provider.id}" value="debit">
</form>

Expect Output:
according to option_value, display radio buttons

Solution

  • You can get all the form-check-input radio inputs and then filter each by their value. The filter will only keep elements in the array whose value is not in the option_value array. You can then loop over this filtered array and hide the elements.

    See working example below:

    const option_values = [{
        id: "trans",
        options: ["bank", "credit"]
      },
      {
        id: "fund",
        options: ["bank"]
      }
    ];
    
    const id = "trans";
    const options = option_values.find(({id:x}) => x===id).options;
    
    [...document.getElementsByClassName("form-check-input")].filter(({
      value
    }) => !options.includes(value)).forEach(elem => elem.style.display = 'none');
    <form>
      <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-bank transfer-${provider.id}" value="bank" title="bank" checked>
      <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-credit-${provider.id}" value="credit" title="credit">
      <input class="form-check-input" name="sending-${provider.id}" type="radio" id="provider-send-debit-${provider.id}" value="debit" title="debit">
    </form>