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;
}
Related
I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..
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>
I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp
Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);
I am trying to create a "contact us" forum with html.
This is my current html:
<form id="contact_form" name="contact_form" method="post" action="validate()">
<div class="row">
<label for="name" class="desc" style="font-size: 30px;">Your name:</label><br />
<input id="name" class="input" name="name" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="email" class="desc" style="font-size: 30px;">Your email:</label><br />
<input id="email" class="input" name="email" type="text" value="" size="50" /><br />
</div><br /><br />
<div class="row">
<label for="message" class="desc" style="font-size: 30px;">Your message:</label><br />
<textarea id="message" class="input" name="message" rows="8" cols="50"></textarea><br />
</div>
<div class="row"><br />
<input id="submit_button" type="submit" value="Send email"/>
</div>
</form>
And my javascript:
function validate() {
//Make sure name is filled out
var x = document.forms["contact_form"]["name"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
//Make sure email is filled out
var x = document.forms["contact_form"]["email"].value;
if (x == null || x == "") {
alert("Email must be filled out");
return false;
}
//Make sure message is filled out
var x = document.forms["contact_form"]["message"].value;
if (x == null || x == "") {
alert("Message must be filled out");
return false;
}
//Validate email
var x = document.forms["contact_form"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos< 1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid email");
return false;
}
}
For some reason when I hit "submit" it takes me to a page called "validate()" How can I make it so that when I click submit it EXECUTES the function validate(), not just take me to a page called validate()...
NOTE: Nevermind the php, right now focus on the html and javascript
It redirects it to that page because you are setting the action to go there. That does not execute JavaScript. You are looking for onsubmit.
Change action="validate()" to onsubmit="return validate();"
And as always, it would be better to set it unobtrusively instead of inline.