I use JavaScript to validate my form but the JavaScript can only validate a field at a time which means I have to duplicate the JavaScript for every field that I want to validate.
For Example,
My form has the Phone and Email fields that I want to validate, To achieve that, I had to write the javascript with the phone ID separately and write the javascript with the email ID separately.
Is it possible to validate the phone and email fields independently but with one javascript file and different ids?
My Sample code is below;
<!--THIS SCRIPT ONLY VALIDATES THE PHONE FIELD -->
<!--TO VALIDATE THE EMAIL FIELD, I HAVE TO DUPLICATE THIS SCRIPT AND CHANGE THE IDS TO email -->
$('.validate').hide();
$('body').on('blur', '#phone', function() {
var value = $(this).val();
if (isphoneInUse(value)) {
alert ("Phone In Use!\nPlease provide another one");
$(".validate").hide();
} else {
$(".validate").show();
}
});
$('#submitForm()').on('submit', function(e) {
var value = $("#phone").val();
if (isphoneInUse(value)) {
// validation failed. cancel the event
console.log("not submitting");
return 0;
}
})
function isphoneInUse(phone) {
return (phone === "1234" || phone === "23456")
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form action='' method='POST' id="submitForm" runat="server" >
<div class="validate" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Phone Available ✓</b></span></div>
<input type="phone" name='phone' required='' id="phone" placeholder="0000-000-0000"/>
<br/><br/>
<div class="validate2" style="display: none;"><span style="color: #4ead55; font-size: x-small;"><b>Email Available ✓</b></span></div>
<input type="email" name='email' required='' id="email" placeholder="hello#youremail.com"/>
</div>
<br/><br>
<button class="button" id="submitForm" type="submit" value=""><span>Check </span></button>
</form>
Related
// What I am Trying to do is to use php and insert my subscribers of Websites In A database first here is
// my html code
<center>
<form action="members.php" method="post">
<h1 class="title-4">Subscribe For Our Latest Updates</h1>
<input type="text" name="name" id="name" placeholder="Enter Your Full Name">
<div class="error-name" style="display:none">
<p>Please Enter Your Name </p>
</div>
<input type="email" name="email" id="email" placeholder="Enter Your E-mail" >
<div class="error-email" style="display:none">
<p>Please Enter a Password Password must be greater than 7 characters </p>
</div>
<input type="submit" name="submit" id="sub" class="name-sub email-sub" value="Subscribe">
</form>
</center>
<div class="sub-pop">
<center>
<h1 class="title-5">
★Thanks For Subscribing ★
</h1>
</center>
</div>
<script src="home.js"></script>
// here is the php Code in members.php
if(isset($_POST['submit'])) {
$connection=mysqli_connect('localhost','root','','lolovers');
$name = $_POST['name'];
$email = $_POST['email'];
$query = "INSERT INTO subscribers(name,email)";
$query .= "VALUES ('$name','$email')";
$subscribe=mysqli_query($connection,$query);
header('Location:home.php');
}
// This is the code to insert my user name and emails in my data base php admin
// here is my javascript that I use to validate my information
// Pop up form for subscribers javascript code
const popUp = document.querySelector('.title-5');
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const subscribe = document.querySelector('#sub');
const errorName = document.querySelector('.error-name')
const errorEmail = document.querySelector('.error-email')
subscribe.addEventListener('click',subscription());
function subscription(e) {
if(name.value==="") {
errorName.style.display = "block"
}
else if (email.value==="") {
errorEmail.style.display = "block"
}
else if (name.value && email.value==="") {
errorName.style.display = "block"
errorEmail.style.display = "block"
e.preventDefault()
}
else {
popUp.style.display="block"
}
}
// The reason why I am using php and javascript is because I have a hard time to display an error message
in php so instead of validating using php I use javascript to validate my form information and I use php
insert the data in php myadmin. The error messages I want to display is in
<div class="error-name" style="display:none">
<p>Please Enter Your Name </p>
</div>
// I want to use javascript so that when some one does not enter his name this div section display under
the form
<div class="error-email" style="display:none">
<p>Please Enter a Password Password must be greater than 7 characters </p>
</div>
// the same thing above I want this div section to display when some one does not enter his email
//somehow my javascript does not work properly when i try to refresh the page my div sections display
automatically even though I did not enter any information it just displays. it even display my thank you
section
<div class="sub-pop">
<center><h1 class="title-5">
★Thanks For Subscribing ★
</h1></center>
</div>
// I also want my php code to not insert the data in the database when the information is not valid
you unnecessarily complicate the task, html5 natively offers this kind of control, without having to add any line of additional code unless you want to customize them.
Just add the required attribute on these fields
form {
display: table;
margin: 1em auto; /* horizontal centering */
padding: .7em;
border: 1px solid grey;
}
input, button {
display: block;
margin:.5em;
float: left;
clear: both;
}
<form action="members.php" method="post">
<h4>Subscribe For Our Latest Updates</h4>
<input type="text" name="name" placeholder="Enter Your Full Name" required >
<input type="email" name="email" placeholder="Enter Your E-mail" required >
<button type="submit">Subscribe</button>
</form>
there is many tutorials on the web to explain this.
You also get precise information on MDN -> https://developer.mozilla.org
Hi successfully made a form where there are two submit buttons.
I needed two buttons because I need each button to take the form to a different place, while get/post the information in the first form.
This is how I did it
Javascript:
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" input name="pick" required value="<?php echo isset($_POST['pick']) ? $_POST['pick'] : ''; ?>"/>
</div>
<input type="button" onclick="submitForm('page2.php')" class="btn small color left" value="ADD ANOTHER STOP" />
<input type="button" onclick="submitForm('page3.php')" class="btn medium color right" value="Continue" />
</form>
It works, both buttons submits to the relevant pages.
But now there is one problem I can't seem to fix, previously if the form was not filled, and i clicked submit, it would ask me to fill up the required fields, now it does not anymore.
If required fields are not filled up, it still submits the form.
I need button 1 to not require required fields to be filled up, and button 2 to require it as button 2 submits the form, while button 1 brings it to a new form to fill up with other details before they submit from there.
Anyone know of a way I can sort this?
You can try this: <input type="text" name="pick" id="pick" required/> and in the javascript
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
if (document.getElementById('pick').value) {
form.submit();
}}
else{
alert('Please fill the required field!');}
You just need to use jquery to validate the form when the first button is clicked and you can use formaction attribute on the button to specify where the button should go when it's clicked.
$('document').ready(function(){
$('#btn1').on('click',function(){
var pick = $('input[type="text"][name="pick"]').val();
if(pick == ""){
alert("enter pick");
return false;
}else{
$(this).submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" name="pick" value="your value">
</div>
<button type="submit" formaction="page2.php" class="btn small color left" id="btn1">ADD ANOTHER STOP</button>
<button type="submit" formaction="page3.php" class="btn medium color right">Continue</button>
</form>
You could use jQuery for this.
if ($('#something').length)
This will check if there exist an element with the id 'something', but not if it is empty or which value it has.
To check this you can use:
if($('#something').val().length>0)
or
if($('#something').val() != "")
Do with it what ever is needed.
You could even add this check within your submitForm function just above the current code.
Try this:
<script>
function submitForm(action) {
var a = $("input[name=pick]").val();
if(a) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
} else {
alert('please fill the required field');
return false;
}
}
</script>
Using this way(simple way):--
<form id="myForm" name="myForm" onSubmit="encriptar_rc4();return false;">
<input type="submit" name="submitOne" value="submitOne" class="submitButton" />
<input type="submit" name="submitTwo" value="submitTwo" class="submitButton" />
</form>
<script>
$(function(){
$(".submitButton").click(function(e){
alert($(this).attr("name"));
});
encriptar_rc4();{
alert('hola');
}
});
</script>
I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();
Here is the code, I can't figure out why enter/return isn't working! Is it because it's inline?
HTML
<div class="wrap"><form name="login" style="margin: 0px">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<input TYPE="text" NAME="pass" size="17" onKeyDown="e.keyCode == 13;" id="fname" class="cool"><br><input type="button" value="LOGIN" class="asbestos-flat-button" onClick="TheLogin(this.form)">
</form>
</div>
JS
<script language="JavaScript" type="text/javascript">
<!--- PASSWORD PROTECTION SCRIPT
function TheLogin() {
var password = 'password';
if (this.document.login.pass.value == password) {
top.location.href="home.html";
}
else {
location.href="index.html";
}
}
// End hiding --->
</script>
I'm learning JS so any help would be so awesome!
UPDATE
Thanks for your help. Still not working when integrated. The page doesn't load the home.html when I hit enter/return. Instead I get no refresh, and the address bar has the url http://example.com/?pass=password.
If I click the button it does load the home.html!
thanks!
Here I wrote a JSFiddle with the working example.
In the HTML code:
Remove onKeyDown="e.keyCode == 13;" from the <input> text element.
Remove onClick="TheLogin(this.form)" from the <input> button element.
Change the type of input button from 'button' to 'submit'. In this way, when you press "enter" in the input text form the form is submitted.
Intercept the "submit" event in the form, adding onSubmit="theLogin(this.form)" on <form> element.
Note: I have renamed the function name from "TheLogin" to "theLogin" because in JavaScript the functions begins with lowercase letters if they are not constructors.
The HTML code:
<div class="wrap">
<form name="login" style="margin: 0px" onSubmit="theLogin(this.form)">
<label for="fname">CLICK TO ENTER PASSWORD</label>
<INPUT TYPE="text" NAME="pass" size="17" id="fname" class="cool">
<br>
<input type="submit" value="LOGIN" class="asbestos-flat-button">
</form>
</div>
And the JavaScript code:
theLogin = function() {
var password = 'password';
if (this.document.login.pass.value === password) {
top.location.href = "home.html";
} else {
location.href = "index.html";
}
}
You have missed the <input type="submit">, without it you can't use the Enter key to submit the form.
I have a mailchimp form to sign up for my email list, and mixpanel tracking to detect when the form is submitted.
<!-- Begin MailChimp Signup Form -->
<div id="mc_embed_signup"><form id="mc-embedded-subscribe-form" class="validate" action="http://fileoptic.us7.list-manage.com/subscribe/post?u=a1a176055d942403ee4c74a11&id=028333dc80" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank"><label for="mce-EMAIL">Subscribe to our mailing list for blog updates:</label>
<input id="mce-EMAIL" class="email" name="EMAIL" required="" type="email" value="" placeholder="email address" />
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input name="b_a1a176055d942403ee4c74a11_028333dc80" type="text" value="" /></div>
<div class="clear"><input id="mc-embedded-subscribe" class="button" name="subscribe" type="submit" value="Subscribe" /></div>
</form></div>
<!--End mc_embed_signup-->
<script type="text/javascript">
mixpanel.track_forms("#mc-embedded-subscribe-form", "Subscribed to Email List");
</script>
I want to extract the submitted email address from the form and use mixpanel.alias to identify users by their email addresses as they navigate around my site.
What code do I use to extract the email address and call mixpanel.alias with it?
I don't know anything about mixpanel, but here are two ways to get the value of an input and store it in a variable for later use.
With jQuery (I prefer this method):
$('#mc-embedded-subscribe-form').on('submit', function(){
var val = $('input.email').val();
console.log(val); // Use this to test the function
});
Or with plain Javascript. First add this to the form tag in your HTML:
onsubmit="getEmail()"
Then the JS function:
function getEmail() {
var elem = document.getElementById('mce-EMAIL');
var val = elem.value;
console.log(val); // For testing
}
Hope that helps :)