How to create simple JavaScript error message from form submission? - javascript

I am new to JavaScript, bought Jon Duckett's book, but am not a fan of the way he described creating/displaying error messages- Can someone please tell me how to just display an error message if the NAME field is left empty? Thank you. Below is the HTML for my form:
<form action="form.php" method="post">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" required="required"><br>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"><br>
<label for="telephone">Telephone:</label><br>
<input type="text" name="telephone" id="telephone">
</fieldset>
<br>
<fieldset>
<legend>Your Information:</legend>
<p>
<label for="service">What service are you inquiring about?</label>
<select name="service" id="service">
<option value="Collision">Collision</option>
<option value="Mechanical">Mechanical</option>
<option value="Custom">Custom</option>
<option value="Other">Other</option>
</select>
</p>
<label for="comments">Comments:</label>
<br>
<textarea name="comments" id="comments" rows="4" cols="40"></textarea>.
<input type="submit" value="Submit"/>
</fieldset>
</form>

Checkout this link, this link shows how to do a simple JavaScript form validation
https://www.w3schools.com/js/js_validation.asp
HTML Code
<form name="myForm" onsubmit="return validateForm()" action="form.php" method="post">
<fieldset>
<legend>Your Details:</legend>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label><br>
<input type="text" name="email" id="email"><br>
<label for="telephone">Telephone:</label><br>
<input type="text" name="telephone" id="telephone">
</fieldset>
<br>
<fieldset>
<legend>Your Information:</legend>
<p>
<label for="service">What service are you inquiring about?</label>
<select name="service" id="service">
<option value="Collision">Collision</option>
<option value="Mechanical">Mechanical</option>
<option value="Custom">Custom</option>
<option value="Other">Other</option>
</select>
</p>
<label for="comments">Comments:</label>
<br>
<textarea name="comments" id="comments" rows="4" cols="40"></textarea>.
<input type="submit" value="Submit"/>
</fieldset>
</form>
JavaScript Code
function validateForm() {
var x = document.forms["myForm"]["name"].value;
if (x === "") {
alert("Name must be filled out");
return false;
}
}
Check functionality here
https://codepen.io/anon/pen/QvNGMZ

You have to create a new element ( span, div ... ), and write an error into it, and append that element after\before your form field, which ocured that error. As a good way, you may make an object, like {fieldName:{errorMessage,validationRule}} , where is fieldName - is your field name, that you need to validate, and errorMessage - is error, which you showing on error, and the validationRule - is regexp, for example, telling you how to validate that field. Or you just may hardcode all of these params. :)
P.s. There are a lot of ways to validate form, to get errors, and to show them. You may really easy search for it and choose the best for yourself.

Related

How can I disable submit button after required html5 return true on the javascript?

My html code like this :
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit">
</form>
I'm using required HTML5 attribute to validate fields.
If user does not input text, it will display HTML5 error.
I want to disable the submit button if any of the required fields are left empty.
How can I do it?
You can disable the pointer events on the button with CSS.
form:invalid>#submit {
pointer-events: none;
}
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit" id="submit">
</form>
You could also disable the button using Javascript.
function disableField() {
const invalidForm = document.querySelector('form:invalid');
const submitBtn = document.getElementById('submit');
if (invalidForm) {
submitBtn.setAttribute('disabled', true);
} else {
submitBtn.disabled = false;
}
}
disableField();
const inputs = document.getElementsByTagName("input");
for (let input of inputs) {
input.addEventListener('change', disableField);
}
<form>
<label for="name">* Name</label>
<input type="text" id="name" required><br>
<label for="name">* Address</label>
<input type="text" id="address" required><br>
<input type="submit" value="Submit" id="submit">
</form>
you can do it after true
$("#button").prop("disabled", true);
You can try something like this:
$(function() {
$("#input-text").keyup(function () {
if($("#input-text")[0].checkValidity()){
$('#submit-button').attr('disabled', 'disabled');
}else{
$('#submit-button').removeAttr('disabled');
}
});
})($);
<form id="newRecord">
<input type="text" required id="input-text"/>
<button form="newRecord" type="submit" id="submit-
button">Submit</button>
</form>
An more generic solution for multiple forms and supporting multiple inputs and buttons.
It detects the change event directly on forms individually, and then change the disabled attribute for all submit types
function disableFormSubmit(form) {
const buttons = form.querySelectorAll(
'button[type="submit"], input[type="submit"]'
);
const disableButtons = () =>
buttons.forEach(el => (el.disabled = form.matches(":invalid")));
form.addEventListener("change", disableButtons);
disableButtons();
}
document.querySelectorAll("form").forEach(disableFormSubmit);
<form action="/">
<legend>First form</legend>
<input type="text" required> <br>
<input type="Checkbox" required> required checkbox <br>
<input type="submit">
<button type="submit">Button submit</button>
</form>
<hr>
<form action="/">
<legend>Second form</legend>
<select required>
<option value="" disabled selected>Select one</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select> <br>
<input type="radio" required name="radio"> required radio <br>
<input type="submit">
<button type="submit">Button submit</button>
</form>
Personally i would go on an solution using only CSS as a visual cue, unless you need the disabled attribute

Pass form data to redirected page - javascript - jQuery

<div class="box-wrapper">
<form method="POST" action="/cgi-bin/formmail/FormMail.pl">
<input type="hidden" name="recipient" value="mail123#gmail.com">
<input type="hidden" name="subject" value="Contact Form">
<input type="hidden" name="redirect" value="http://127.0.0.1/contact.html?formsubmit=success">
<input type="text" name="name" placeholder="Name" required="">
<input type="email" name="email" placeholder="Email Id" required="">
<input type="text" name="mobile" maxlength="10" placeholder="Mobile Number" id="number" required="">
<input name="service" list="services" placeholder="What service you need?" required>
<datalist id="services">
<option value="Web Design">Web Design</option>
<option value="Graphic Design">Graphic Design</option>
<option value="UI/UX Design">UI/UX Design</option>
<option value="Digita Marketing">Digital Mareketing</option>
<option value="Others">Others</option>
</datalist>
<textarea placeholder="Additonal detail" name="details" required=""></textarea>
<button type="submit" name="submit" id="submit-btn" onclick="thanksMsg()"><i class="fa fa-send"></i></button>
</form>
<div id="thanksmsg"></div>
</div>
This is my html code.I'm passing form data to my mail after submit. and redirecting to "http://127.0.0.1/contact.html?formsubmit=success". On this page i display thanks msg using jQuery.
<script type="text/javascript">
$(document).ready(function(){
var url = window.location.href;
var text = $('#form').find('input[name="name"]').val();
if(url == 'http://127.0.0.1:8887/contact.html?formsubmit=success'){
var name = $('#form').find('input[name="name"]').val();
$('#thanksmsg').append('<p>Hi'+text+', Thanks for reaching us out. <br>We will get back to you shortly 😉</p><div><a class="cta-btn">Back to home</a><a class="cta-btn">View our Portfolio<a></div>');
$('form').css('display', 'none');
}
});
</script>
here in thanks msg i wanted to show the name entered in input field. but as it gets redirected it doesn't appear. how to display the name?
Try to use cookies. At the form submit, write something like $.cookie('name', name). To recover you call $.cookie('name').
I'm not sure if it'll work, because in some cases the cookies are erased, but is easy to try.

getElementById() returns null on first element

The following code is my simple registration form. The problem is that alert(elements[0].value) displays undefined instead of the value of name (which is the first element of my form). However, if I try to execute alert(elements[1].value), it displays the value of name without any problem. Any ideas?
<html>
<body>
<form name="register" id="register" method="POST" action="this-file.php">
<fieldset>
<legend><span style="color:red; font-size:20px">
Register</span></legend><br>
<label for="firstname">First name<span style="color:red;">*</span></label>
<input type="text" name="firstname" id="firstname" placeholder="Peter"
autofocus required><br><br>
<label for="lastname">Last name<span style="color:red;">*</span></label>
<input type="text" name="lastname" id="lastname" placeholder="Parker"
required><br><br>
<label for="password">Password<span style="color:red;">*</span></label>
<input type="password" name="password" id="password" required><br><br>
<label for="favfood">Favorite food<span style="color:red;">*</span></label>
<select name="favfood" id="favfood" required>
<option value="" selected>(none)</option>
<option value="chicken">Chicken</option>
<option value="pizza">Pizza</option>
<option value="pasta">Pasta</option>
<option value="hamburger">Hamburger</option>
<option value="steak">Steak</option>
</select>
<p>Gender<span style="color:red;">*</span></p>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" required>
<label for="male">Male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" required>
<label for="female">Female</label>
</li>
</ul>
</fieldset><br>
<input type="submit" value="Register" name="register">
<input type="reset" value="Clear form" name="clear"><br><br>
</form>
<script type="text/javascript">
var form = document.getElementById('register');
var elements = form.elements;
form.noValidate = true;
form.addEventListener('submit', function (event) {
alert(elements[0].value); //displays "undefined" -- why?
for (var i = 0; i < elements.length; i++) {
if (elements[i].hasAttribute("required")) {
if (!elements[i].checkValidity()) {
event.preventDefault();
alert('Please, fill in every required field.');
form.reset();
elements[0].focus();
break;
}
}
}
}, false);
</script>
</body>
</html>
The first element in the elements collection is the <fieldset>. It doesn't have a name or a value.
(Yes, I know it doesn't really make sense for elements to include fieldsets, but it does).
Test the value of theelement.tagName to see if you are dealing with an input/select/textarea before trying to run your validation routine on it.

Generating form fields using jquery

I have a pretty basic form that allow user to post simple classified ads. It looks like this:
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset>
<h3>Car Informations</h3>
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
Add More Ads
</fieldset>
</form>
I would like to allow the visitor to post more ads then one via "Add More Ads" button/link which would generate same 3 fields as much times as visitor needs ads.
What would be the simplest solution to do this? Any help/guide would be great!
Thanks!
P.S Also it would be great if the user could also remove the fields if he doesnt need them
Try this.
$('#addMOre').on('click',function(){
var self = $('.apendable').first().clone().insertAfter(".apendable:last");
$('.apendable:last input').val('');
self.append('<button class="close-info">close</button>');
$('.close-info').on('click', function(){
$(this).parent().remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset id="info">
<h3>Car Informations</h3>
<div class="apendable">
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
</div>
Add More Ads
</fieldset>
</form>
You can set inputs in <div class="row"> then copy first row class.
$("#addAdsFiels").click(function(){
var clone = $(this).siblings(".row:first").clone();
$(clone).find("input").val("");
$(this).before(clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset>
<h3>Car Informations</h3>
<div class="row">
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
</div>
Add More Ads
</fieldset>
</form>

HTML web form mailto not working issue

I need help, I am new to HTML5. I build a HTML5 web form and try to use mailto function to send out. But when I try to do it on my android device with chrome browser, it shows:
Webpage not available
Anyone can help ?
<form method="post" action="mailto:myname#gmail.com" enctype="text/plain">
<p>
<label for ="firstname" class="text">First Name:</label>
<input type="text" name="firstname" id="firstname" />
</p>
<p>
<label for ="lastname">Last Name:</label>
<input type="text" name="lastname" id="lastname" />
</p>
<p>
<label for ="hkid">HK Identity Card:</label>
<input type="date" name="dob" id="dob" />
</p>
<p>
<label for="sex" class="select">Sex:</label>
<select name="sex" id="sex" data-native-menu="false">
<option value="option1">Male</option>
<option value="option2">Female</option>
</select>
</p>
<p>
<label for="mobile"> Mobile:</label>
<input type="tel" name="mobile" id="mobile" />
</p>
<p>
<label for="hometel">Resident Phone:</label>
<input type="tel" name="hometel" id="hometel" />
</p>
<p>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" />
</p>
<p>
<label for ="date">Appointment Date(DD-MM-YYYY)</label>
<input type="date" name="date" id="date" value="" />
</p>
<p>
<label for="session" class="select">Session :</label>
<select name="session" id="session" data-native-menu="false">
<option value="option1">AM</option>
<option value="option2">PM</option>
</select>
</p>
<input type="submit" value="Send" />
<input type="reset" value="Reset" />
</form>
mailto: as a form action simply is not well supported.
Use an HTTP(S) form action and send the email from your server instead of the user's (possibly non-existent) email client.
The solution is to use the control panel and go to folder options.
Open the "File Types" tab.
There find the entry "URL: MailTo Protocol" ... highlight it and click "advanced".
Now highlight "open" and click "edit".
You will probably find outlook express as the mailto program.
Change "application to use" as follows:
"C:\Documents and Settings\HP_Administrator\Local Settings\Application Data\Google\Chrome\Application\chrome.exe" https://mail.google.com/mail?extsrc=mailto&url=%1
The path within the quote marks is whatever is the correct path on your machine to chrome.exe.
The Application: chrome
That's it.

Categories