Unable to select form with querySelector - javascript

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 class="inputF">
<div class="inputD">
<label for="fname" >Full Name</label>
<input type="text" id="fname" required>
</div>
<div class="inputD">
<label for="uname">Username</label>
<input type="text" id="uname">
</div>
<div class="inputD">
<label>Email address</label>
<input type="email" id="Email" placeholder="example#gmail.com" required >
</div>
<div class="inputD">
<label for="phn">Phone Number</label>
<input type="number" id="phn">
</div>
<div class="inputD">
<label for="pass">Password</label>
<div class="pass">
<input type="password" class="P IptP" required>
<i class="fa fa-eye-slash show-hide"></i>
</div>
</div>
<div class="inputD">
<label for="cpass">Confirm Password</label>
<div class="pass">
<input type="password" class="CP IptP" required>
<i class="fa fa-eye-slash show-hide"></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 ?

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

Form data is not uploaded and alert not working

I'm new to Javascript and followed a tutorial to make a pop form. The data filled by the user was supposed to appear in the console and that doesn't happen. I would also like to create an alert for when people click on the submit button so I added the last few lines that you'll see in the JavaScipt code, but it's not working as well. Hope that this is detailed enough and that someone can help me.
Here is the HTML
<h1>
I'd love to chat with you about your upcoming project.
</h1>
<div class="intro-text">
Fill out the form bellow to get in touch. Either for a budget information or to book a meeting to discuss
any ideas that you might have, you can contact me for any
clarification you need. I'll get back to you in 2-3 days.
</div>
<div class="row open-form">
<div class="open-btn">
<button id="show-modal"><strong>Open Form</strong></button>
</div>
</div>
<script src="./JavaScript/action_page.js"></script>
<div class="modal modal--hidden">
<div class="modal_content">
<div class="close">
<i class="fas fa-times" onclick="closeMe()"></i>
</div>
<h1>Ask away</h1>
<form id="submit">
<input type="text" placeholder="Name" name="name" />
<input type="email" id="email" placeholder="Email" name="email"/>
<input type="text" placeholder="Subject" name="subject" />
<textarea placeholder="Message" name="message"></textarea>
<button class="submit">Submit</button>
</form>
</div>
</div>
And JavaScript
document.getElementById("show-modal").addEventListener("click", function() {
document.querySelector(".modal").style.display = "flex";
});
function closeMe() {
document.querySelector(".modal").style.display = "none";
}
document.querySelector("#show-modal").addEventListener("submit", event => {
event.preventDefault();
toggleModal();
let formData = new FormData(document.querySelector("#show-modal"));
console.log(
"Name:" + formData.get("name"),
"Email:" + formData.get("email"),
"Subject:" + formData.get("subject"),
"Message:" + formData.get("message")
);
});
document.getElementById("#show-modal").addEventListener("submit", function() {
alert("Thank you for your message!");
});
Here is the page if you want to have a look: https://giacomosorbi.github.io/joanaoli09-module-i/contact.html
Change the code to:
(Removed toggleModal() as there is no defination for it)
document.getElementById("show-modal").addEventListener("click", function() {
document.querySelector(".modal").style.display = "flex";
});
function closeMe() {
document.querySelector(".modal").style.display = "none";
}
document.querySelector("#submit").addEventListener("submit", event => {
event.preventDefault();
let formData = new FormData(document.querySelector("#submit"));
console.log(
"Name:" + formData.get("name"),
"Email:" + formData.get("email"),
"Subject:" + formData.get("subject"),
"Message:" + formData.get("message")
);
alert("Thank you!!!");
});
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>
I'd love to chat with you about your upcoming project.
</h1>
<div class="intro-text">
Fill out the form bellow to get in touch. Either for a budget information or to book a meeting to discuss
any ideas that you might have, you can contact me for any
clarification you need. I'll get back to you in 2-3 days.
</div>
<div class="row open-form">
<div class="open-btn">
<button id="show-modal"><strong>Open Form</strong></button>
</div>
</div>
<script src="./JavaScript/action_page.js"></script>
<div class="modal modal--hidden">
<div class="modal_content">
<div class="close">
<i class="fas fa-times" onclick="closeMe()"></i>
</div>
<h1>Ask away</h1>
<form id="submit">
<input type="text" placeholder="Name" name="name" />
<input type="email" id="email" placeholder="Email" name="email"/>
<input type="text" placeholder="Subject" name="subject" />
<textarea placeholder="Message" name="message"></textarea>
<button class="submit">Submit</button>
</form>
</div>
</div>
First of all, move <script> tag on the end of the html document, because you are trying to find elements in html that aren't rendered yet.
As so:
<div class="modal modal--hidden">
<div class="modal_content">
<div class="close">
<i class="fas fa-times" onclick="closeMe()"></i>
</div>
<h1>Ask away</h1>
<form id="submit">
<input type="text" placeholder="Name" name="name" />
<input type="email" id="email" placeholder="Email" name="email"/>
<input type="text" placeholder="Subject" name="subject" />
<textarea placeholder="Message" name="message"></textarea>
<button class="submit">Submit</button>
</form>
</div>
</div>
<script src="./JavaScript/action_page.js"></script>
Second, your addEventListener("submit",... should be on form element, not on modal button-

checkValidity() not showing any html5 error notifications when fields are empty and posting with Ajax

I have a form that posts using Ajax, I also want to set an HTML5 required attribute on some input fields, but this stops working as expected with Ajax.
So I did the following:
$("body").on("click",".register-button",function(e){
e.preventDefault();
if($('#registerform')[0].checkValidity()){
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
}else{
}
});
This way the form is not posted when empty, but I also don't get any notifications that fields are empty like I would get when only using HTML to post.
I also tried logging the validity like so:
$("body").on("click",".register-button",function(e){
e.preventDefault();
$check = $('#registerform')[0].checkValidity();
console.log($check);
registerform = $(".register-form").serialize();
$.ajax({
type:'post',
url:"includes/registreren.php",
data:({registerform: registerform}),
success:function(data){
var content = $( $.parseHTML(data) );
$( "#registerresult" ).empty().append( content );
}
});
});
Which shows false in my console when empty. So the code works, why are the HTML5 notifications not shown? I remember doing something similar in the past and I didn't have to add any custom error messages then, it just worked.
This is my HTML markup:
<form id="registerform" class="register-form" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="voornaam" placeholder="Voornaam" required>
</div>
<div class="col-md-6">
<input type="text" name="achternaam" placeholder="Achternaam" required>
</div>
<div class="col-md-12">
<input type="text" name="bedrijf" placeholder="Bedrijfsnaam (optioneel)">
</div>
<div class="col-md-6">
<input type="text" name="telefoon" placeholder="Telefoonnummer" required>
</div>
<div class="col-md-6">
<input type="text" name="email" placeholder="E-mail" required>
</div>
<div class="col-md-3">
<input type="text" name="huisnummer" id="billing_streetnumber" placeholder="Huisnummer" required>
</div>
<div class="col-md-3">
<input type="text" name="tussenvoegsel" placeholder="Tussenvoegsel" required>
</div>
<div class="col-md-6">
<input type="text" name="postcode" id="billing_postcode" placeholder="Postcode" required>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-md-6">
<input type="text" name="straat" placeholder="Straatnaam" readonly required>
</div>
<div class="col-md-6">
<input type="text" name="woonplaats" placeholder="Woonplaats" readonly required>
</div>
</div>
</div>
<div class="col-md-6">
<input type="password" name="password" placeholder="Wachtwoord (minimaal 6 tekens)" required>
</div>
<div class="col-md-6">
<input type="password" name="confirmpassword"placeholder="Herhaal wachtwoord" required>
</div>
<div id="registerresult">
</div>
</div>
<button type="button" name="submit" class="register-button">Account aanmaken</button>
</form>
What am I missing?

Load the values twice into two input fields onload

I am using local storage to save the username in the first-page.html and retrieving it into the second-page.html
But if I have two or more places in my second-page.html where I want the username to be retrieved, how can I achieve it using two different ids. Since the id once used cannot be used in another input field.
Can anyone please help.
Index.html:
<script>
function save(){
var fieldValue = document.getElementById('user').value;
localStorage.setItem('text', fieldValue);
}
</script>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" onclick="save()" />
SecondPage.html
<script>
function load(){
var storedValue = localStorage.getItem('text');
if(storedValue){
document.getElementById('here').value = storedValue;
}
}
</script>
<body onload="load()">
<!-- first div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group">
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
<!-- second div -->
<div class="form-group">
<div class="cols-sm-10">
<div class="input-group"> // change the id here
<input type="text" name="userName" id="here" class="form-control" placeholder="Username" required>
</div>
</div>
</div>
</body>
Just give each element different ids, really. No problem with that. And then when you set, set both:
if (storedValue) {
document.getElementById('here').value = storedValue;
document.getElementById('my-other-id').value = storedValue;
}

Multi forms datas into array via Javascript

I have some forms like this:
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
....
<div class="well">
<form>
<span class="remove pull-right"><i class="fa fa-times pointer"></i></span>
<div class="form-group" style="margin:0">
<label for="image-link">Image Link</label>
<input type="text" name="image-link" value="" class="form-control" >
</div>
<div class="form-group" style="margin:0">
<label for="content">Content</label>
<textarea class="form-control" name="content" rows="10"></textarea>
</div>
<div class="form-group" style="margin:0">
<label for="author">Author</label>
<input type="text" name="author" value="" class="form-control" >
</div>
</form>
</div>
The forms will be added more and more when I click the add button, so will have multi forms.
I want to submit multi datas into an json arrayjust looks like this:
"quotes":[
{"image":"image_link","content":"content","author:"author"}
{"image":"image_link","content":"content","author:"author"}
...
{"image":"image_link","content":"content","author:"author"}
]
which is an array will contain all of the forms' datas. And the amount of forms is not fixed. It will be changed when I click add button.
So how can I do that automatically.
Thank you so much!
You can iterate through all the form elements on the page by calling the following function:
function generateArrayData() {
var forms = document.querySelectorAll(".well form");
var quotes = [];
for(var i = 0; i < forms.length; i++) {
var form = forms[i];
quotes.push({
image: form.querySelector("input[name='image-link']").value,
content: form.querySelector("textarea").value,
author: form.querySelector("input[name='author']").value
})
}
return quotes;
}
The way this works is that querySelectorAll loads all of the form elements on the page within a div with the class .well. We then iterate through the elements from the previous query and use querySelector to pull out each individual element we'd like to extract.

How to empty ajax loaded form?

How can we empty a ajax loaded form using pure JavaScript or jQuery.
I have tried document.forms[0].reset(); and $('#new-staff-form')[0].reset(); both didn't work it returns undefined.
Update
<div class="box col-md-12 new-staff">
<form id="new-staff-form" method="post">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" name="f_name" placeholder="First name"/>
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" name="l_name" placeholder="Last name"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="user_name">User name</label>
<input id="user_name" type="text" name="user_name" placeholder="User name"/>
</div>
<div class="col-md-6">
<button id="user-avail" class="btn btn-primary">Check available</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary pull-left">Save</button>
</div>
</div>
</form>
</div>
Javascript:
$('#new-item').click(function(){ // works fine until I load new html form using ajax with same ids and class
$('#new-staff-form')[0].reset();
$('.new-staff').slideToggle(); // show new form
});
$('.edit-item').click(function(){ // ajax call this loads everything correctly
var id = $(this).data('staf_id'); //item to delete
$.ajax({
url:url_view_staff+id,
type:'get'
}).done(function(data){
edit_item_id = id;
$('.new-staff').html(data).slideDown();
}).fail(function(data){
$('#errors').html(data.responseText);
$('.valid-error').slideDown();
});
});
JavaScript:
document.getElementById("myForm").reset();
Jquery :
$('#form_id')[0].reset();
Make sure your form id is valid.
FIDDLE
$('#configreset').click(function(){
$('#configform')[0].reset();
});

Categories

Resources