I added the onclickevent to the button, but it still doesn't output my form correctly.
By default, buttons inside a form have a type of submit, which means that the button will automatically submit the form when clicked.
To fix, the quickest way would be to add a type="button" property to your button:
function clearErrors() {
document.getElementById("firstnameError").innerHTML = "";
document.getElementById("lastnameError").innerHTML = "";
document.getElementById("usernameError").innerHTML = "";
}
function processForm() {
clearErrors();
var output = "";
if (document.getElementById("firstname").value == "") {
document.getElementById("firstnameError").innerHTML = "First name required";
}
if (document.getElementById("lastname").value == "") {
document.getElementById("lastnameError").innerHTML = "Last name required";
}
output += "The form would submit the following information:"
output += "\nFirst name: " + document.getElementById("firstname").value;
output += "\nLast name: " + document.getElementById("lastname").value;
if (document.getElementById("male").checked == true) {
output += "\nSex: Male";
} else {
output += "\nSex: Female";
}
if (document.getElementById("car").checked == true) {
output += "\nI have a car";
}
var education = document.getElementById("education");
output += "\nEducation: " + education.options[education.selectedIndex].text;
document.getElementById("output").value = output;
}
<div id="header">
<h1>HTML Forms</h1>
</div>
<div id="content">
<form id="detailsForm">
<p>
First name:<input type="text" name="firstname" id="firstname" />* <span id="firstnameError"></span><br /> Last name:<input type="text" name="lastname" id="lastname" />* <span id="lastnameError"></span><br /> Username:
<input type="text" name="username" id="username" />* <span id="usernameError"></span><br /> Male <input type="radio" name="sex" value="male" id="male" /> Female<input type="radio" name="sex" value="female" id="female" checked /> <br /> I have a
car:<input type="checkbox" name="vehicle" value="Car" id="car" /><br /> Select a Level of Education:<br />
<select name="education" id="education">
<option value="Secondary School">Secondary School</option>
<option value="University">University</option>
</select> <br />
<button type="button" onclick="processForm()">Click me</button>
</p>
<p>
<textarea name="output" id="output" rows="10" cols="100"></textarea>
</p>
</form>
</div>
I recreated your code as a snippet. It's working fine.
(Modified your code to have the eventListener() added in JS and not in HTML.)
function clearErrors() {
document.getElementById("firstnameError").innerHTML = "";
document.getElementById("lastnameError").innerHTML = "";
document.getElementById("usernameError").innerHTML = "";
}
function processForm() {
clearErrors();
var output = "";
if (document.getElementById("firstname").value == "") {
document.getElementById("firstnameError").innerHTML = "First name required";
}
if (document.getElementById("lastname").value == "") {
document.getElementById("lastnameError").innerHTML = "Last name required";
}
output += "The form would submit the following information:"
output += "\nFirst name: " + document.getElementById("firstname").value;
output += "\nLast name: " + document.getElementById("lastname").value;
if (document.getElementById("male").checked == true) {
output += "\nSex: Male";
} else {
output += "\nSex: Female";
}
if (document.getElementById("car").checked == true) {
output += "\nI have a car";
}
var education = document.getElementById("education");
output += "\nEducation: " + education.options[education.selectedIndex].text;
document.getElementById("output").value = output;
}
var btnSubmit = document.getElementById('btnSubmit')
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
processForm()
})
<div id="header">
<h1>HTML Forms</h1>
</div>
<div id="content">
<form id="detailsForm">
<p>
First name:<input type="text" name="firstname" id="firstname" />* <span id="firstnameError"></span><br /> Last name:<input type="text" name="lastname" id="lastname" />* <span id="lastnameError"></span><br /> Username:
<input type="text" name="username" id="username" />* <span id="usernameError"></span><br /> Male <input type="radio" name="sex" value="male" id="male" /> Female<input type="radio" name="sex" value="female" id="female" checked /> <br /> I have a
car:
<input type="checkbox" name="vehicle" value="Car" id="car" /><br /> Select a Level of Education:<br />
<select name="education" id="education">
<option value="Secondary School">Secondary School</option>
<option value="University">University</option>
</select> <br />
<button id="btnSubmit">Click me</button>
</p>
<p>
<textarea name="output" id="output" rows="10" cols="100"></textarea>
</p>
</form>
</div>
Related
How can I submit my form after satisfying my form validation function? I need it to redirect to my homepage. I'm thoroughly stumped. Is it possible to use an <input type="button"> instead of an <input type="submit"> to still submit the form? If not how could I use the submit button to first run my form validation function before submitting?
My HTML:
<form name="registerform" ID="registerform">
<div ID="Namebox">
<p>Name</p>
<input type="text" id="name" name="name" />
<br />
</div>
<br />
<div ID="emailbox">
<p>Email</p>
<input type="text" id="email" name="email" size="30"/>
<br />
</div>
<br />
<div ID="passwordbox">
<p>Password</p>
<input type="password" ID="password"/>
<br />
</div>
<br />
<div ID="confirmpasswordbox">
<p>Confirm Password</p>
<input type="password" ID="confirmpassword" onkeyup="passwordvalidator()"/>  <span id="doesnotmatch"></span>
<br />
</div>
<br />
<div ID="citystatebox">
<p>City, State</p>
<input type="text" id="citystate"name="citystate"/>
<br />
</div>
<br />
<br />
On-Snow Disciplines
<br />
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Downhill Skiing"/> Downhill Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Downhill Snowboarding"/> Downhill Snowboarding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Cross-Country Skiing"/> Cross-Country Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Backcountry Skiing"/> Backcountry Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Backcountry Snowboarding/Splitboarding"/> Backcountry Splitboarding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Park Skiing"/> Park Skiing
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Park Riding"/> Park Riding
<br />
  <input type="checkbox" name="onsnowdisciplines" value="Ski Mountaineering"/> Ski Mountaineering
</p>
<br />
<br />
<input type="button" id="registerSubmitButton" onclick="regSubBut()" value="Send It">   <span id="errorInformer" style="color:red;"></span>
</form>
My JS:
function regSubBut() {
var error = document.getElementById("errorInformer");
var email = document.getElementById("email");
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (document.getElementById("name").value === "")
{
error.innerHTML = "Please enter a name";
document.getElementById("name").focus();
return false;
}
else if (email === "" || !emailFilter.test(email.value))
{
error.innerHTML = "Please enter a valid email";
email.focus();
return false;
}
else if (document.getElementById("password").value === "" || document.getElementById("confirmpassword").value === "")
{
error.innerHTML = "Please enter a password";
document.getElementById("password").focus();
return false;
}
else if (document.getElementById("citystate").value === "")
{
error.innerHTML = "Please enter a city and state";
document.getElementById("citystate").focus();
return false;
}
else {
return true;
var frm = document.getElementById("registerform");
frm.action = "Homepage.html";
frm.submit();
document.getElementById("welcomebutton").style.display = "block";
}
}
I see a problem with your code when there are no validation errors:
else {
return true;//below line won't execute, move it to the bottom
var frm = document.getElementById("registerform");
frm.action = "Homepage.html";
frm.submit();
document.getElementById("welcomebutton").style.display = "block";
}
You can use the onsubmit attribute of the form tag:
var valid = function() {
return false;
};
<form onsubmit="return valid();">
Won't submit ...
<input type="submit" />
</form>
You can also use the onclick attribute of the input tag:
var valid = function() {
return false;
};
<form>
Won't submit either ...
<input type="submit" onclick="return valid();" />
</form>
$('form')[0].checkValidity()
If above is executed assuming that you just have form element on this page this will perform validation ( HTML 5 validation ) and you don't need to use default submit.
[SOLVED] I have a script that copies text from text fields to text area. My question is how can I upgrade this script so it would copy labels to? Or if I could somehow add extra text before field value?
This is my HTML:
<label>Input1: </label> <input type="text" name="i1" class="entry" id="field_1" value="" /> <br />
<label>Input2: </label> <input type="text" name="i2" class="entry" id="field_2" value="" /><br />
<label>Input3: </label> <input type="text" name="i3" class="entry" id="field_3" value="" /><br />
<label>Input4: </label> <input type="text" name="i4" class="entry" id="field_4" value="" /><br />
<label>Input5: </label> <input type="text" name="i5" class="entry" id="field_5" value="" /><br /><br />
<input type="button" name="b" value="copy" /><br /><br />
<textarea class="box" name="t" rows="5"> </textarea>
And this:
<script type="text/javascript">
$( document ).ready(function() {
$("input:button").click(function() {
var values = "";
$("input:text").each(function(i) {
values += (i > 0 ? "\n" : "") + this.value;
});
$("textarea").val(values);
});
});
</script>
EDIT: Is there any way of not showing text if some of the text fields are empty?
I added if(this.value.length > 1) and when copy is pressed it shows "undefined".
try
$( document ).ready(function() {
$("input:button").click(function() {
var values = "";
$("input:text").each(function(i) {
var text=$(this).prev("label").text();
values+=text+" " ;
values += (i > 0 ? "\n" : "") + this.value;
});
$("textarea").val(values);
});
});
DEMO
I can't figure out why but my script is not working properly as it was working fine before. Now, it is not working anymore and I can't figure out why as I don't remember making any changes to the script tag.
<body>
<form id="contact">
<fieldset id="contactInformation">
<legend>Contact Information</legend>
<p id="error"></p>
<label for="name">Name:</label>
<br>
<input id="name" type="text">
<br>
<br>
<label for="phoneNumber">Phone Number:</label>
<br>
<input id="phoneNumber" type="text">
<br>
<br>
<label id="eMail">E-Mail Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="city">City:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
<label id="province">Province</label>
<br>
<select id="province">
<option>Choose Your Province</option>
<option>Alberta</option>
<option>British Columbia</option>
<option>Manitoba</option>
<option>New Brunswick</option>
<option>Newfoundland and Labrador</option>
<option>Northwest Territories</option>
<option>Nova Scotia</option>
<option>Nunavut</option>
<option>Ontario</option>
<option>Prince Edward Island</option>
<option>Quebec</option>
<option>Saskatchewan</option>
<option>Yukon Territory</option>
</select>
<br>
<br>
<div id="shipping">
<label id="shippingCheckbox">Is your shipping information the same as your contact information?</label>
<br>
<br>
<input type="checkbox" id="sameInfo">
<label>Yes it is</label>
<br>
<br>
</div>
<fieldset id="shippinginformation">
<legend>Shipping Information</legend>
<label for="phoneNumber">Phone Number:</label>
<br>
<input id="phoneNumber" type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
</fieldset>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<br>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
//script.js
var errorNotify = 'Sorry, we could not process your request because '
var errorField = [];
function formVal() {
var isValid = true;
for (var i = 0; i < errorField.length; i++ ) {
$(errorField[i]).removeClass('error');
}
errorField = [];
if(!nameCheck()) {
isValid = false;
}
if(!phoneCheck()) {
isValid = false;
}
if (isValid === false) {
$('#error').html(errorNotify).hide().slideDown('slow');
for (var i = 0; i < errorField.length; i++) {
$(errorField[i]).addClass('error');
}
errorNotify = 'Sorry, we could not process your request because ';
}
function nameCheck(){
if ($('#name').val() === '') {
errorNotify += ' you did not enter your name.';
errorField.push($('#name'));
return false;
} else {
return true;
}
}
function phoneCheck(){
var phoneCheck = $('#phoneNumber').val();
if (phoneCheck === '') {
errorNotify += ' you did not enter your phone number.';
errorField.push($('#phoneNumber'));
return false;
} else if (phoneCheck.length !== 10) {
errorNotify += 'please enter a 10 digit phone number';
errorField.push($('#phoneNumber'));
}
else if (isNaN(parseInt(phoneCheck))) {
errorNotify += 'you have entered a letter, please enter a number';
errorField.push($('#phoneNumber'));
}
else {
return true;
}
}
return isValid;
}
$(function () {
$('#contact').submit(function() {
return formVal();
});
$('#sameInfo').change(function() {
if ($(this).is(":checked")) {
alert('this is a test');
} else {
alert('this is not a test');
}
});
});
Not that it should fail totally because of this, but you're missing return values on your else if's in the phoneCheck() function.
Other than that it looks fine imo.
Trying to get my final project ready on time (for once) but I cannot seem to get the radio-button group to validate when submitting the form. I have everything else working, and validation is so-so, however, the radio group is being stubborn. I've tried different ways such as removing the variable and pointing directly to the 'group1' but nothing has worked. Any help would be greatly appreciated.
<script type="text/javascript">
function ValidateContactForm()
{
var name = document.ContactForm.Name;
var email = document.ContactForm.Email;
var phone = document.ContactForm.areaCode;
var what = document.ContactForm.Subject;
var comment = document.ContactForm.Comment;
var btn = document.ContactForm.group1;
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
if (email.value == "")
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf("#", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0)
{
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (btn.value > 0) {
window.alert("Please choose method of contact.");
btn.focus();
return false;
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
if (what.selectedIndex < 1)
{
alert("Please tell us how we can help you.");
what.focus();
return false;
}
if (comment.value == "")
{
window.alert("Please provide a detailed description or comment.");
comment.focus();
return false;
}
}
function validateFixedLengthNumericField(numericField, len){
if (len != numericField.value.length){
numericField.focus();
alert('Field must contain exactly '+len+' numbers.');
}
}
function validateNextField(numericField, len, nextField){
if (len == numericField.value.length){
nextField.focus();
}
}
</script>
<form method="post" onSubmit="return ValidateContactForm();" name="ContactForm">
<div align="center">
<table border="2">
<tr>
<td valign="top"><h3 align="left">Contact Information</h3>
<p align="left">Name:<br /> <input type="text" size="65" name="Name"></p>
<p align="left">E-mail Address:<br /><input type="text" size="65" name="Email"></p>
<p align="left">Telephone:<br />
<div class="Telephone" style="float:left;">
(<input name="areaCode" id="areaCode" type="text" maxlength="3"
onkeyup="validateNextField(this,3,phonePrefix);"
onblur="validateFixedLengthNumericField(this,3);"
style="font-size:11px; width:20px;" title="Area Code" autocomplete="off">)
<input name="phonePrefix" id="phonePrefix" type="text"
onkeyup="validateNextField(this,3,phoneSuffix);"
onblur="validateFixedLengthNumericField(this,3);"
style="font-size:11px; width:20px;" maxlength="3" title="Phone Prefix" autocomplete="off">-
<input name="phoneSuffix" id="phoneSuffix" type="text" maxlength="4"
onkeyup="validateNextField(this,3,phoneExtension);"
onblur="validateFixedLengthNumericField(this,4);"
style="font-size:11px; width:25px;" title="Phone Suffix" autocomplete="off"></p>
</div>
<p align="left"> </p>
<p align="left"><strong>Would you like to sign up for one of our mailings?</strong> <br />
</p>
<div align="left">
<input type="checkbox" name="option" value="newsletter" />
Newsletters<br />
<input type="checkbox" name="option" value="events" />
Events<br />
<input type="checkbox" name="option" value="grando" />
Grand Openings<br />
<input type="checkbox" name="option" value="coupon" />
Coupons<br />
<input type="checkbox" name="option" value="other" />
Other</div>
<p align="left"><strong>How do you perfer us to contact you</strong><br />
</p>
<div align="left">
<input type="radio" name="group1" id="r1" value="1" />
Phone
<br />
<input type="radio" name="group1" id="r2" value="2" />
Email<br />
<input type="radio" name="group1" id="r3" value="3" />
Snail Mail
</div>
<p align="left">What can we help you with?
<select type="text" value="" name="Subject">
<option> </option>
<option>Customer Service</option>
<option>Question</option>
<option>Comment</option>
<option>Complaint</option>
<option>Other</option>
</select></p>
<p align="left">Comments:</p>
<p align="center">
<textarea cols="55" rows="10" name="Comment"></textarea>
</p>
<p align="center"><input type="submit" value="Send" name="submit"><input type="reset" value="Reset" name="reset">
</form>
In your case variable btn contains an array of radio buttons. So you need to loop through it and find which one is checked. Something like:
var somethingChecked = false;
for (i = 0; i < btn.length; i++) {
if (btn[i].checked) {
somethingChecked = true;
}
}
if (!somethingChecked) {
window.alert("Please choose method of contact.");
return false;
}
I have been trying to make a form that validates phone number and name, but whenever submit is entered it just inputs the same messages whether the fields are filled out or not. The message constantly appears and I can't figure it out
ETA: http://jsfiddle.net/6W3uU/
<body>
<form id="contact">
<fieldset id="contactInformation">
<legend>Contact Information</legend>
<p id="error"></p>
<label id="name">Name:</label>
<br>
<input type="text">
<br>
<br>
<label id="phoneNumber">Phone Number:</label>
<br>
<input type="text">
<br>
<br>
<label id="eMail">E-Mail Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="address">Address:</label>
<br>
<input type="text">
<br>
<br>
<label id="city">City:</label>
<br>
<input type="text">
<br>
<br>
<label id="postalCode">Postal Code:</label>
<br>
<input type="text">
<br>
<br>
<label id="province">Province</label>
<br>
<select id="province">
<option id="choose">Choose Your Province</option>
<option id="alberta">Alberta</option>
<option id="britishColumbia">British Columbia</option>
<option id="manitoba">Manitoba</option>
<option id="newBrunswick">New Brunswick</option>
<option id="newfoundland">Newfoundland and Labrador</option>
<option id="northwestTerritories">Northwest Territories</option>
<option id="noviaScotia">Nova Scotia</option>
<option id="nunavut">Nunavut</option>
<option id="ontario">Ontario</option>
<option id="pei">Prince Edward Island</option>
<option id="quebec">Quebec</option>
<option id="saskatchewan">Saskatchewan</option>
<option id="yukon">Yukon Territory</option>
<br>
<br>
<br>
<label id="shippingCheckbox">Is your shipping information the same as your contact information?
<input type="radio" id="sameInfo">
<label>
Yes it is
</label>
<br>
<br>
<input type="radio" id="notSameInfo">
<label>
No it is not
</label>
<br>
<br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
<br>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
And here is the script:
//script.js
var errorNotify = 'Sorry, we could not process your request because '
var errorField = [];
function formVal() {
var isValid = true;
for (var i = 0; i < errorField.length; i++ ) {
$(errorField[i]).removeClass('error');
}
errorField = [];
if(!nameCheck()) {
isValid = false;
}
if(!phoneCheck()) {
isValid = false;
}
if (isValid === false) {
$('#error').html(errorNotify).hide().slideDown('slow');
for (var i = 0; i < errorField.length; i++) {
$(errorField[i]).addClass('error');
}
errorNotify = 'Sorry, we could not process your request because ';
}
function nameCheck(){
if ($('#name').val() === '') {
errorNotify += ' you did not enter your name.';
errorField.push($('#name'));
return false;
} else {
return true;
}
}
function phoneCheck(){
var phoneCheck = $('#phoneNumber').val();
if (phoneCheck === '') {
errorNotify += ' you did not enter your phone number.';
errorField.push($('#phoneNumber'));
return false;
} else if (phoneCheck.length !== 10) {
errorNotify += 'please enter a 10 digit phone number';
errorField.push($('#phoneNumber'));
}
else if (isNaN(parseInt(phoneCheck))) {
errorNotify += 'you have entered a letter, please enter a number';
errorField.push($('#phoneNumber'));
}
else {
return true;
}
}
return isValid;
}
$(function () {
$('#contact').submit(function() {
return formVal();
});
});
You have your ids on the label tags, not the input fields, change
<label id="name">Name:</label>
<br>
<input type="text">
to
<label for="name">Name:</label>
<br>
<input id="name" type="text">
etc