如何使用javascript(而非jquery)按值删除/隐藏单选按钮。 我有三个具有动态ID和名称的单选按钮。 我想知道如何通过值删除单选按钮
我卡住了,不确定在页面加载时如何使用javascript
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
答案 0 :(得分:1)
您可以获得所有form-check-input
单选输入,然后按其值过滤每个输入。过滤器将仅将值不在option_value
数组中的元素保留在数组中。然后,您可以遍历此过滤后的数组并隐藏元素。
请参见下面的工作示例:
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>
答案 1 :(得分:0)
如果使用jquery
$(':radio').each(function(){
$(this).css('display', option_value.indexOf($(this).val()) === -1 ? 'none':'');
})
option_value是array [string]