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