简体   繁体   中英

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?

 <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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