skip to Main Content

Its my code in html :

subscribe

<label for="visaBtn">Visa</label>
<input type="radio" name ="card" id="visaBtn">
<label for="mastercardBtn">MasterCard</label>
<input type="radio" name="card" id="mastercardBtn">
<label for="paypalBtn">Paypal</label>
<input type="radio" name="card" id="paypalBtn"><br>
<button id="myCheckBox">submit</button>
<script src="index.js"></script>

body>

Then I wrote this function on JavaScript but when I am trying it on the browser it isn't working.

document.getElementById("myButton").onclick=function(){

const myCheckBox =document.getElementById("myCheckBox");
const visaBtn = document.getElementById("visaBtn");
const mastercardBtn = document.getElementById("mastercardBtn");
const paypalBtn = document.getElementById("paypalBtn");

if(myCheckBox.checked){
    console.log("You are subscribed");
}
else{
    console.log("You are NOT subscribed!");
}
 if(visaBtn.checked){
    console.log("You are paying with a Visa!");
 }
 else if(mastercardBtn.checked){
    console.log("You are paying with a Mastercard!");
 }
 else if(paypalBtn.checked){
    console.log("You are paying with a Paypal!");
 }
 else{
    console.log("You must select a payment type!");
 }

I want to know what’s wrong with my code?

2

Answers


  1. the id of the button is wrong
    should be "myButton"

    ```<button id="myButton">submit</button> ```
    
         document.getElementById("myButton").onclick = function () { 
                const myCheckBox = document.getElementById("myCheckBox");
                const visaBtn = document.getElementById("visaBtn");
                const mastercardBtn = document.getElementById("mastercardBtn");
                const paypalBtn = document.getElementById("paypalBtn");
            
                if (myCheckBox.checked) {
                    console.log("You are subscribed");
                } else {
                    console.log("You are NOT subscribed!");
                }
                if (visaBtn.checked) {
                    console.log("You are paying with a Visa!");
                } else if (mastercardBtn.checked) {
                    console.log("You are paying with a Mastercard!");
                } else if (paypalBtn.checked) {
                    console.log("You are paying with a Paypal!");
                } else {
                    console.log("You must select a payment type!");
                }
            };
    
    Login or Signup to reply.
  2. I think you have to do two changes.

    1. first give the path for index.js as -> (<script src="./index.js"></script>)
    2. use the correct button id to catch dom element ->(document.getElementById("myCheckBox")...)

    please check and let us know whether it’s working or not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search