Home > Blockchain >  Unable to select form with querySelector
Unable to select form with querySelector

Time:02-06

I'm trying to select a form element in javascript using the querySelector but it won't work and sometime it returns the form element.

Here's my code:

JavaScript

const ele = document.querySelector('form');
console.log(ele);
ele.addEventListener('submit', function(e) {
    console.log("in the eventlister function");
    const pass = document.getElementsByClassName("P")[0].value;
    const cpass = document.getElementsByClassName("CP")[0].value; 
    const messagePara =document.getElementById("generated_message");
    if(pass != cpass){
        e.preventDefault();
        messagePara.textContent ="check your password!!";
                            messagePara.style.color= 'red';
                            return false;
    }
    else{
        messagePara.textContent ="";
    }
});

HTML

 <form >
                <div >
                    <label for="fname" >Full Name</label>
                    <input type="text" id="fname" required>
                </div>
                <div >
                    <label for="uname">Username</label>
                    <input type="text" id="uname">
                </div>
                <div >
                    <label>Email address</label>
                    <input type="email" id="Email" placeholder="[email protected]" required >    
                </div>
                <div >
                <label for="phn">Phone Number</label>
                    <input type="number" id="phn">
                </div>
                <div >
                    <label for="pass">Password</label>
                    <div >
                        <input type="password"   required>
                        <i ></i>
                    </div>
                </div>
                <div >
                    <label for="cpass">Confirm Password</label>
                    <div >
                        <input type="password"   required>
                        <i ></i>
                    </div>
                </div>
                    <div>
                    <button id="save_btn" >Continue</button>
                   </div> 
                </form>

I tried adding class for the form and select the form using the ClassName but still the same problem occurred. How can I fix this problem ?

CodePudding user response:

When manipulating the DOM with a <script> in the <header>, you'll want to wait until the document has loaded.

document.body.addEventListener('load',function(){
  // Your DOM sensitive code here
});

otherwise, you might want to include your script after the form tag

<!DOCTYPE html>
<html>
<!-- Your header; moving your script from here -->
<body>
<!-- Your form here -->
<!-- Move script here-->
<script>
// DOM sensitive code here as the last element in the body
</script>
</body>
  • Related