Enable button functionality - javascript

I have this form that the functionality is when all the required fields are completed to enable the submit button.
It was working until i added more interaction for a map gallery.
What could be wrong?
Im open to any suggestion or advice.
Im pretty new
Html
<h1>Contact me</h1>
<form action="" id="ContactForm" onsubmit="sConsole(event)">
<fieldset>
<p><label for="fullname">First Name:</label></p>
<input type="text" id="fullname" name="fullname" required />
<p><label for="lastname">Last Name:</label></p>
<input type="text" id="lastname" name="lastname" >
<p><label for="email">Email:</label></p>
<input type="email"id="email" email="email" required />
<p>Comment</p>
<label>
<textarea name="comments" id="comments" cols="30" rows="30" placeholder="Insert your comments here..." required ></textarea>
</label>
<p>Date of birth</p>
<label for="mydate">Pick a date:</label>
<input type="date" id="date" required />
<input type="submit" id="SubmitButton" disabled = "disabled" value="submit" onClick="sConsole()">
</fieldset>
Javascript
ContactForm.addEventListener("input" , () => {
if (fullname.value.length > 0 &&
lastname.value.length > 0 &&
email.value.length > 0 &&
comments.value.length > 0 &&
date.value.length > 0) {
SubmitButton.removeAttribute("disabled");
} else {
SubmitButton.setAttribute("disabled","disabled");
}
});
The new things that i added
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
const mapGallery = document.querySelectorAll(".maps-gallery");
let currentlySelected = 0;
prevBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected--;
mapGallery[currentlySelected].classList.add("active");
nextBtn.disabled = false
if (currentlySelected === 0){
prevBtn.disabled = true;
}
});
nextBtn.addEventListener("click",function(){
mapGallery[currentlySelected].classList.remove("active");
currentlySelected++;
mapGallery[currentlySelected].classList.add("active");
prevBtn.disabled = false
if (mapGallery.length === currentlySelected +1 ){
nextBtn.disabled = true;
}
});

You need to use
document.getElementById("ContactForm").addEventListener
in the code. In this case, JavaScript needs to know the ID of the element to access.

Related

How can I get an animation to run when input submit is clicked in javascript?

I have a form which I want each time I validate if the information is empty, to run an animation of a library that imports from CSS called Animate.CSS, so I have created a function to validate each input, so if one is empty, it runs an "shake" animation of the library I mentioned. At the same time, the class has to be added, but removed at the end in case the user does not write in the input again, the animation runs.
This is my form:
<form action="" id="form">
<label for="name">Name</label>
<input
type="text"
placeholder="Name"
id="name"
minlength="3"
required
/>
<br />
<label for="email">Email</label>
<input type="email" placeholder="Emai" id="email" required />
<br />
<label for="subject">Subject</label>
<input
type="text"
placeholder="Subject"
id="subject"
minlength="3"
required
/>
<br />
<label for="message">Message</label>
<textarea
name="message"
id="message"
minlength="5"
placeholder="Message"
required
style="resize: none; height: 200px"
></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>
And Javascript:
(function () {
var form = document.getElementById("form"),
name = form.name,
email = form.email,
subject = form.subject;
message = form.message;
function validateName(e) {
if (name.value == "" || name.value == null) {
form.classList.add("animate__animated");
name.classList.add("animate__shakeX");
e.preventDefaul();
} else {
console.log("error");
}
}
function validateEmail(e) {
if (email.value == "" || email.value == null) {
email.classList.add("animate__animated");
email.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateSubject(e) {
if (subject.value == "" || subject.value == null) {
subject.classList.add("animate__animated");
subject.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateMessage(e) {
if (subject.value == "" || subject.value == null) {
message.classList.add("animate__animated");
message.classList.add("animate__shakeX");
e.preventDefaul();
}
}
function validateForm(e) {
validateName(e);
validateEmail(e);
validateSubject(e);
validateMessage(e);
}
form.addEventListener("submit", validateForm);
});
This code works, apparently, but it happens when I click on refresh and not when I click on submit:
var form = document.getElementById("name");
if (form.value == "" || form.value == null) {
form.classList.add("animate__animated");
form.classList.add("animate__shakeX");
}
There was a lot going on in there so I simplified some stuff to make a little more sense to me but you should go through your code and check for errors as there are quite a few there. I have made a little demo of what I assume you wanted the form to do.
document.getElementById("form").addEventListener("submit", (e) => {
validateName();
validateEmail();
validateSubject();
validateMessage();
e.preventDefault();
setTimeout(removeAnimations, "2000");
})
function validateName() {
const name = document.getElementById("name");
if(name.value.length < 3) {
name.classList.add("animate__red", "animate__animated");
} else {
name.classList.remove("animate__red");
}
}
function validateEmail() {
const ele = document.getElementById("email");
if(ele.value.length < 1) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function validateSubject() {
const ele = document.getElementById("subject");
if(ele.value.length < 3) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function validateMessage() {
const ele = document.getElementById("message");
if(ele.value.length < 3) {
ele.classList.add("animate__red", "animate__animated");
} else {
ele.classList.remove("animate__red", "animate__animated");
}
}
function removeAnimations() {
document.querySelectorAll(".animate__red")
.forEach((ele) => {
ele.classList.remove("animate__red", "animate__animated");
});
}
.animate__red {
background-color: red;
}
<form action="" id="form">
<label for="name">Name</label>
<input type="text" placeholder="Name" id="name" minlength="3" />
<br />
<label for="email">Email</label>
<input type="email" placeholder="Email" id="email" />
<br />
<label for="subject">Subject</label>
<input type="text" placeholder="Subject" id="subject" minlength="3" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" minlength="5" placeholder="Message" style="resize: none; height: 200px"></textarea>
<br />
<button type="submit" class="paper-btn" id="submit">
Send message
</button>
</form>

enabling submit btn after filling form (all inputs) with javascript no jquery

I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!
Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.
The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Javascript AND (&&) operator is not working inside if block

I have a JavaScript login validation block, however my if block is partially working, i.e condition after the AND(&&) is not being checked resulting not applying validation on password, here is my code snippet.
function validateLogin(){
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if((userid.value.length < 3) && (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style","color:red")
document.getElementById('user_error').innerHTML="invalid username/password.";
return false;
}
return true;
}
<form id="login_form" name="login" onsubmit=" return validateLogin()" >
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder ="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder ="Password">
<p id ="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN" >
It's optimization of if. If first part is false, then further comparisons are not executed because of false && Anything results in false
You need to compare using OR
function validateLogin() {
var userid = document.getElementById('user_id');
var passid = document.getElementById('pass_id');
if ((userid.value.length < 3) || (passid.value.length < 6)) {
document.getElementById('user_error').setAttribute("style", "color:red")
document.getElementById('user_error').innerHTML = "invalid username/password.";
return false;
}
return true;
}
<form id="login_form" name="login" onsubmit=" return validateLogin()">
<div>
<input class="user_login_form" id='user_id' type="text" required tabindex="1" name="user_id" autofocus autocomplete=off placeholder="User Name">
</div>
<div>
<input class="user_login_form" id='pass_id' required type="password" tabindex="2" name="user_pass" placeholder="Password">
<p id="user_error"></p>
</div>
<input class="user_login_submit" type="submit" id='btnLogin' tabindex="3" name="login_btnSubmit" value="LOGIN">
You want to use OR here. So your throw your error if userid length is less than 3 OR passid length is less than 6.
if((userid.value.length < 3) || (passid.value.length < 6))

JQuery HTML form validation still triggers email with blank entries

I have an HTML form with three mandatory fields in. I don't want the form to submit the AJAX call if they are empty.
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid = true;
if( $('input[name="Name"]').val() == '' || $('input[name="Email"]').val() == '' || $('input[name="Phone"]').val() == '') {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
<form id="contact" name="contact" method="post" action="">
<label for="Name">Name: *</label>
<input type="text" name="Name" id="name" />
<input name="robotest" type="hidden" value="" />
<label for="Position">Position:</label>
<input type="text" name="Position" id="position" />
<label for="Company">Company:</label>
<input type="text" name="Company" id="company" />
<label for="Address">Address:</label>
<input type="text" name="Address" id="address" />
<label for="Email">Email: *</label>
<input type="text" name="Email" id="email" />
<label for="Email">Phone number: *</label>
<input type="text" name="Phone" id="phone" />
<label for="Event_Subject">What is the subject of the event?:</label>
<input type="text" name="Event_Subject" id="subject" />
<label for="Event_Date">What is the date of the event?:</label>
<input type="text" name="Event_Date" id="date" />
<label for="Additional_info">Additional Information:</label>
<br />
<textarea name="Additional_info" rows="20" cols="20" id="info"></textarea>
<input id="formsubmitted" type="submit" name="submit" value="submit" class="submit-button" />
</form>
This does give the popup box if you try and fill it in empty, but I have received an email with all blank fields.
How is the user getting past the validation and managing to send the form through blank?
More than likely you've not popped in a preventDefault() in there, so the form is doing a normal (non-AJAX) post after your function ends. What's the method/action on your form? Perhaps there doesn't need to be an action at all?
Try this:
$("#contact").submit(function(e){
e.preventDefault();
var ajaxurl = '<?php echo WEB_URL; ?>contact_send.php';
var data = $(this).serializeArray();
console.log(data);
var valid;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
} else {
valid = false;
}
if(valid) {
$.post(ajaxurl, data, function (response) {
$(".show_homecontact_form_success").fadeIn(1000);
$("#contact")[0].reset();
});
} else {
alert('Please fill in all mandatory fields.');
}
});
As Jigar pointed out, you can shorten the code by assigning an initial value to the valid variable and removing else block:
var valid = false;
if( $('input[name="Name"]').val().length > 0
&& $('input[name="Email"]').val().length > 0
&& $('input[name="Phone"]').val().length > 0) {
valid = true;
}

Categories