Sen
Sen

Reputation: 773

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

Upvotes: 0

Views: 509

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50759

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>

Upvotes: 1

Invalid
Invalid

Reputation: 66

if you use jquery

$(':radio').each(function(){
    $(this).css('display', option_value.indexOf($(this).val()) === -1 ? 'none':'');
})

option_value is array[string]

Upvotes: 0

Related Questions