如何通过单击特定单选按钮

时间:2016-06-13 18:10:52

标签: javascript

堆叠流量社区的每个人都好

我尝试创建原生javascript函数..... 如果我单击radioyes按钮,我想将特定invoice_wrapper div的背景颜色更改为红色 如果我点击radiono按钮,则为绿色

我希望通过此关键字

执行此操作

我怎么能通过原生javascript而不是任何图书馆来做到这一点

祝你好运.....

    <?php foreach($fetches AS $electricities): ?>

<div class="invoice_wrapper">

<?php if($electricities->paid == "Yes"): ?>

Yes: <input onclick="" class="radioyes" type="radio" name="paid" value="<?php echo $electricities->paid; ?>" checked>
No: <input onclick="" class="radiono" type="radio" name="paid" value="No">

<?php else: ?>

Yes: <input onclick="" class="radioyes" type="radio" name="paid" value="<?php echo $electricities->paid; ?>">
No: <input onclick="" class="radiono" type="radio" name="paid" value="No" checked>

<?php endif; ?>

</div>

<?php endforeach; ?>

1 个答案:

答案 0 :(得分:0)

var elems = document.querySelectorAll('.invoice_wrapper [type="radio"]');
var elemsInit = document.querySelectorAll('.invoice_wrapper [type="radio"]:checked');
var handler = function(elem) {
  elem.parentNode.classList.remove('red', 'green');
  if (elem.value === 'Yes') {
    elem.parentNode.classList.add('green');
  } else {
    elem.parentNode.classList.add('red');
  }
};
Array.from(elemsInit).forEach(handler);
Array.from(elems).forEach(function(elem) {
  elem.addEventListener('change', handler.bind(null, elem));
});
.invoice_wrapper {
  border: 5px solid black;
  margin: 5px;
}
.green {
  background: green;
}
.red {
  background: red;
}
<div class="invoice_wrapper">
  Yes:
  <input class="radioyes" type="radio" name="paid1" value="Yes" checked>No:
  <input class="radiono" type="radio" name="paid1" value="No">
</div>

<div class="invoice_wrapper">
  Yes:
  <input class="radioyes" type="radio" name="paid2" value="Yes">No:
  <input class="radiono" type="radio" name="paid2" value="No" checked>
</div>