I have a form created using HTML and I have a submit button.
I am trying to have the submit button disabled if the fields are not filled out.
However, now even if the fields are filled out the button stays disabled.
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
subButton.disabled = true
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
The issue is, that you never call the function clickedButton(). You need an eventListener that listens for change events within the inputs and then calls that function:
const INPUTS = document.querySelectorAll('input');
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
const subButton = document.querySelector('.sbutton')
const inputTexts = document.querySelector('.input')
const INPUTS = document.querySelectorAll('input');
subButton.disabled = true
INPUTS.forEach(el =>
el.addEventListener('change', clickedButton)
)
function clickedButton() {
if (document.querySelector('.input').value === "") {
subButton.disabled = true
} else {
subButton.disabled = false
}
}
<div class="form">
<section>
<form action=[link] method="POST">
<fieldset>
<legend>Your Contact Info!</legend>
<label class="firstname" for="firstname">First Name</label>
<input class="input" type="text" id="firstname" name="name" placeholder="Your first name" required>
<label class="lastname" for="lastname">Last Name</label>
<input type="text" id="lastname" name="lname" placeholder="Your last name">
<label class="email" for="email">E-mail</label>
<input class="input" type="email" id="email" name="email" placeholder="Your e-mail" required>
<label class="comments" for="comments">Additional Comments</label>
<textarea class="input" placeholder="Anything else we should know!" id="comments" name="comments" required></textarea>
<label class='input' for="timeofday">When is the best time of day to contact you?</label>
<select id="timeofday" name="timeofday">
<option value='Morning'>Morning</option>
<option selected value="afternoon">Afternoon</option>
<option value="evening">Evening</option>
</select>
</fieldset>
<button class="sbutton" type="submit">Submit</button>
Note, that you check only the first input. querySelector returns only 1 element (the first).
Nothing on the page is calling clickedButton()
Attach an EventListener for changes on the form that calls this function.
var form = document.querySelector('form');
form.addEventListener('change', clickedButton);
Also when you are using querySelector you will only get the first element in the form which is a <input .... If you want to check for all you should use querySelectorAll.
But that function would return an array so then you need to check if all of them have text.
In that case you could do it like this.
function validateForm() {
// Get all elements
const elements = document.querySelectorAll("input");
// Filter out elements that have no value, if there is more then 1 set disabled to true, else it is false
const disabled = elements.filter((el) => el.value === "").length > 0 ? true : false;
subButton.disabled = disabled
}
And if you are going with this way you need to call this function instead of the other one like this:
var form = document.querySelector('form');
form.addEventListener('change', validateForm);
Related
I have the following if that, so far, the only thing it does is to not let it trigger the form ajax submission if any input is blank. Being empty is one of the conditions but besides that, I'd also like it to prevent the form from being sent if a required filling pattern for each field is not respected. I've tried some things but they didn't work, so I guess I'm probably making mistakes regarding the synthax or other details. What would be the best way to do it?
(function($){
$('#enquiry').submit( function(event){
event.preventDefault();
var fname = $.trim($('.fname').val());
var lname = $.trim($('.lname').val());
var email = $.trim($('.email').val());
var subject = $.trim($('.subject').val());
var message = $.trim($('.message').val());
if (fname === '' || lname === '' || email === '' || subject === '' || message === ''){
alert('trigger error message')
}
else{
alert('ajax call sending the data')
}
Here's the form code, in case it's relevant:
<form id="enquiry" method="post" onsubmit="return false">
<div class="form">
<input class="input fname" placeholder="a" name="fname" type="text" autocomplete='off' pattern="[a-zA-Z]{1,36}" required></input>
<label for="namef" class="">Your name</label>
</div>
<div class="form">
<input class="input lname" placeholder="a" name="lname" type="text" autocomplete='off' pattern="[a-zA-Z]{1,36}" required></input>
<label for="surname" class="">Your surname</label>
</div>
<div class="form">
<input class="input email" placeholder="a" name="email" type="text" autocomplete='off' pattern="[^#\s]+#[^#\s]+\.[^#\s]+" required></input>
<label for="email" class="">Your email</label>
</div>
<div class="form custom-select">
<select class="input subject" name="subject" autocomplete='off' required>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</div>
<div class="form2">
<textarea class="input message" placeholder="a" name="message" autocomplete='off' pattern="[0-9a-zA-Z- ]" required></textarea>
<label for="tellme" class="">Tell me something</label>
</div>
<div class="contactbutton">
<button type="submit" class="button" role="button"><span>SUBMIT</span></button>
</div>
</form>
For one of my classes we're using JQuery validation. I'm trying to get the answers to populate next to the corresponding text on the bottom that's listed (name, age, date,etc..) on the document below after the user inputs the info in the text box.
<script>
$(document).ready(function() {
$("#input").validate();
$("#input").submit(function(e) {
e.preventDefault(); //Prevents from submitting (which is the default action)
if (!$("#input").valid()) {
return false;
} else {
$("#result").append($("#name").val() + "<br>" + "Your name is");
}
});
});
</script>
<body>
<p><b>Fill out all the fields below and click submit</b></p>
<div>
<label for="name" class="label">Enter your name</label>
<input type="text" name="name" id="name" class="required" title="Please enter your name"> </div><br>
<div>
<label for="thedate" class="label">Enter today's date</label>
<input type="text" name="thedate" id="thedate" class="required date"></div><br>
<div>
<label for="theage" class="label">Enter your age</label>
<input type="text" name="theage" id="theage" class="required digits"></div><br>
<div>
<label for="theurl" class="label">Enter your web site</label>
<input type="text" name="theurl" id="theurl" class="required url"></div><br>
<div>
<label for="theemail" class="label">Enter your email</label>
<input type="text" name="theemail" id="theemail" class="required email"></div><br>
<div>
<input type='submit' value='Submit' name="submit" id='submitme'></div><br>
</form>
<p id="result"></p>
<p><b>Name:</b></p><br>
<p><b>Date: </b></p><br>
<p><b>Age:</b> </p><br>
<p><b>Website: </b></p><br>
<p><b>Email:</b></p><br>
</body>
</html>
I have a text field, which i check to make sure the text field is not empty before submission, which work fine.
How do I make sure that it only checks for the id="Name" text field is not empty and ignore the other text field.
<input type="text" class="form-control" id="Name" aria-label="Name" placeholder="Name" required >
<input type="text" class="form-control" id="address" aria-label="address" placeholder="address">
<input type="text" class="form-control" id="zip" aria-label="zip" placeholder="zip" >
JS
$('input:text').val().length;
Target the element by ID,
$('#Name').val().length;
Did you try this?
$('#Name').val().length;
You have set attribute required to the input with ID Name so form won't submit unless it has some value. If you want to check for whitespaces you can use jquery $.trim() method:
$('form').submit(function(e) {
var name = $('#Name').val();
if ($.trim(name) === '') {
e.preventDefault();
return false;
}
console.log('form submited!');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" class="form-control" id="Name" aria-label="Name" placeholder="Name" required />
<input type="text" class="form-control" id="address" aria-label="address" placeholder="address" />
<input type="text" class="form-control" id="zip" aria-label="zip" placeholder="zip" />
<input type="submit" value="submit" />
</form>
I'm the beginner of JS. I try to get input from the HTML form. And print words out from function. I have read JS in W3. However, it keeps going wrong. Could somebody give me a hand.
HTML - about the form
<form method="get">
<h2>Please leave your contact information for us</h2>
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" name="firstName" placeholder="Your First Name"><br>
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" name="LastName" placeholder="Your last Name"><br>
<label for="email">E-mail:</label>
<input type="e-mail" id="email" name="eMail"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="passWord"><br>
<label for="suGession">sub gesstion:</label><br>
<textarea name="suggestion" id="suGession" cols="30" rows="10"></textarea>
<br>
<br>
<p>What do you usually cook?</p>
<input type="text">
<button type="submit" onclick="welcome()">Give Us Help</button>
</form>
My JS code
var first = document.getElementById("FirstName");
var last = document.getElementById("LastName");
function welcome(){
var welcomeF = "Welcome" + first +" "+ last;
return welcomeF;
}
console.log(welcome());
Use first.value to get the value of the element & use onSubmit attribute in instead of using onclick.
Have a look at this code, I did some changes in your code.
Javacript :
function welcome(){
var first = document.getElementById("FirstName").value;
var last = document.getElementById("LastName").value;
var welcomeF = "Welcome " + first +" "+ last;
console.log(welcomeF);
window.alert(welcomeF);
return false; //To prevent it from going into next page.
}
Html :
<form onSubmit = "return welcome();">
<h2>Please leave your contact information for us</h2>
<label for="FirstName">First Name:</label>
<input type="text" id="FirstName" name="firstName" placeholder="Your First Name"><br>
<label for="LastName">Last Name:</label>
<input type="text" id="LastName" name="LastName" placeholder="Your last Name"><br>
<label for="email">E-mail:</label>
<input type="e-mail" id="email" name="eMail"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="passWord"><br>
<label for="suGession">sub gesstion:</label><br>
<textarea name="suggestion" id="suGession" cols="30" rows="10"></textarea><br><br>
<p>What do you usually cook?</p>
<input type="text">
<button type="submit" >Give Us Help</button>
You need to change:
var welcomeF = "Welcome" + first +" "+ last;
to:
var welcomeF = "Welcome" + first.value +" "+ last.value;
first and last are just references to the dom nodes, not the value in them
I am trying to validate a form. I'm doing this by creating a JS code that ensures all text fields have atleast a character in it and if not the submit button is disabled. However, when i run this code my submit button becomes active after filling out only one field.
Also if you find any bugs etc please point them out, cheers.
This is my HTML
<form name = "form" onsubmit="validate()">
<h3>Please complete the form below. Mandatory fields marked with *</h3>
<fieldset>
<h4>Personal Details</h4>
<p>
<label for="fname">*First Name</label> <input type="text" name="fname" id="fname" placeholder="First Name" onKeyup="validate()" class = "form" >
</p>
<p>
<label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="Etype">Gender</label>
<select class = "form" id="gender" name="gender"><option value="">Select...</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</p>
<p>
<label for="age">*Age</label>
<select class = "form" id="age" name="age"><option value="">Select...</option>
<option value="youngest">3-7</option>
<option value="young">7-12</option>
<option value="teen">12-16</option>
<option value="young-adult">16-18</option>
<option value="adult">18+</option>
</select>
</p>
<p>
<label for="s_add">*Street Address</label> <input type="text" name="s_add" id="s_add" placeholder="Insert Street Address" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="s_sub">*Suburb</label> <input type="text" name="s_sub" id="s_sub" placeholder="Suburb" onKeyup="validate()" class = "form"/>
</p>
<p>
<label for="state">*State</label> <input type="text" name="state" id="state" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="pcode">*Postcode</label> <input type="text" name="pcode" id="pcode" onKeyup="validate()" class = "form" />
</p>
<p>
<label for="phone">*Phone</label> <input type="text" name="phone" id="phone" placeholder="Mobile or Home" onKeyup="validate()" class = "form"/>
</p>
<p>
<label for="email">*Email</label> <input type="text" name="email" id="email" placeholder="Email Address" onKeyup="validate()" class = "form"/>
</p>
</fieldset>
<fieldset>
<h4>Emergency Contact</h4>
<p> please select someone within a close vicinity of 'Clowning Around'. </p>
<p>
<label for="fname">*First Name</label> <input type="text" name="fname" id="fname" onKeyup="validate()" placeholder="First Name" class = "form" />
</p>
<br>
<p>
<label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" onKeyup="validate()" class = "form" />
</p>
<br>
<p>
<label for="s_add"> *Street Address</label> <input type="text" name="s_add" id="s_add" placeholder="Insert Street Address" onKeyup="validate()" class = "form" />
</p>
<br>
<p>
<label for="Mnum"> *Mobile Number</label> <input type="text" name="Mnum" id="Mnum" placeholder="Mobile Number" class = "form" />
</p>
<br>
<p>
<label for="Relationship"> *Relationship</label> <input placeholder="E.g Parent" class = "form"/>
</p>
<br>
<p>
<input id="SubmitButton" type="submit" disabled="disabled" value="Submit" />
</fieldset>
<fieldset>
<h4> Type of Enrollment </h4>
<label for="Etype">*What would you like to enrol in?</label>
<select class = "form" id="Etype" name="Etype"><option value="">Select...</option>
<option value="Camp">Camp</option>
<option value="Class">Class</option>
</select>
</p>
</form>
</body>
</fieldset>
as you can see in my code ive added onKeyup="validate()" in the inputs.
This is my JS
window.onload = function() {
console.log("The window has finished loading");
var SubmitButton = document.getElementById("SubmitButton");
SubmitButton.addEventListener('click', function() {
console.log("The submit button has been clicked");}, false);
var fname = document.getElementById("fname");
fname.addEventListener('keyup', function() {
console.log((fname).value);}, false);
var lname = document.getElementById("lname");
lname.addEventListener('keyup', function() {
console.log((lname).value);
validate();}, false);
}
function validate()
{
var x = document.forms["form"].elements;
var xbutton = true;
for (var i = 0; i < xbutton.length; i++) {
if (x[i].value.length == 0) xbutton = false;
}
if (xbutton) {
document.getElementById('SubmitButton').disabled = !xbutton;
}
}
I've added the first function just in case its related.
Edit:
I've fixed var i = 0; i < xbutton.length; i++
to x.length
Now when i run the code i get an Uncaught TypeError: Cannot read property 'length' of undefined
for line if (x[i].value.length == 0) xbutton = false;
any ideas?
The for loop isn't right, you refer to xbutton.length but it should be x.length because x is the list of elements and xbutton is a boolean:
for (var i = 0; i < x.length; i++) {
Also, you're duplicating the event handlers by using both the inline onkeyup and addEventListener. Use one or the other.
Finally, in the onsubmit handler, you need to return false in order to prevent the form from submitting, if the validation fails.
The new error occurs because you have fieldset elements included in the form.elements list, so you're trying to get the value of a fieldset which doesn't exist. To resolve that, add a condition to check that the element is an input[type=text]:
for (var i = 0; i < x.length; i++) {
if(x[i].tagName == 'INPUT' && x[i].type == 'text'){
if (x[i].value.length == 0) xbutton = false;
}
}