简体   繁体   English

如何使用 JavaScript 在特定单选按钮上应用条件

[英]How to apply Condition on specific Radio Button using JavaScript

What I want is when I click on specific red id Radio Button then it shows me Alert as you can see in the code... in my case its not happening.. what is the issue and how can I sort this?我想要的是,当我单击特定的红色id 单选按钮时,它会向我显示警报,正如您在代码中看到的那样......在我的情况下它没有发生......问题是什么,我该如何排序?

 <form> What color do you prefer?<br> <input type="radio" name="colors" id="red">Red<br> <input type="radio" name="colors" id="blue">Blue </form> <script> if (document.getElementById("red").checked == true) { alert('working'); } </script>

You need an eventListener你需要一个事件监听器

 document.getElementById("red").addEventListener("change", myAlert); function myAlert() { alert('working'); }
 <form> What color do you prefer?<br> <input type="radio" name="colors" id="red">Red<br> <input type="radio" name="colors" id="blue">Blue </form>

  1. You need event listeners - inline event handlers are not recommended您需要事件侦听器 - 不建议使用内联事件处理程序
  2. You need to decide what you are testing您需要决定要测试的内容

Here are two ways to running这里有两种运行方式

They are radios so we do not need to test if they are checked它们是收音机,所以我们不需要测试它们是否被检查过

 window.addEventListener("load",function() { // when the page loads // testing clicking the RED only document.getElementById("red").addEventListener("click",function() { console.log("The specific Red event listener was invoked"); }); // delegation document.querySelector("form").addEventListener("click",function(e) { const tgt = e.target; if (tgt.id==="red") console.log("Clicking in the form, we clicked the thing with ID red") }) });
 <form> What color do you prefer?<br> <label><input type="radio" name="colors" id="red">Red</label><br> <label><input type="radio" name="colors" id="blue">Blue</label> </form>

Try like this:试试这样:

 <form> What color do you prefer?<br> <input type="radio" name="colors" id="red"/>Red<br> <input type="radio" name="colors" id="blue"/>Blue </form> <script> document.getElementById("red").onchange = function() { alert('working'); } </script>

An event handler is needed to run that specific code when a radio button is clicked.单击单选按钮时,需要一个事件处理程序来运行该特定代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM