I have 2 simple JS function one checks values of 2 input fields and triggers the other function Here is the code
function ValidateForm()
{
var name = document.getElementById('fullname').value;
var email = document.getElementById('email').value;
if(name.value= '' || email.value='')
{
alert('fields Empty');
}
else
{
UpdateRecord();
}
}
function UpdateRecord()
{
var Qact = getQueryVariable('ACT');
if(Qact==2){
var picture= document.getElementById('myPic').src;
activity.setUpdates(name,email,picture);
}
else
{
activity.CheckEmail(name,email);
}
}
HTML
<button onClick="ValidateForm();" data-role="button" >Register</button>
if I call UpdateRecord() on button click it works fine but when i use ValidateForm() nothing works. The firefox debugger don't even go to the ValidateForm() Function
if(name.value= '' || email.value='')
should be
if(name === '' || email === '')
if(name.value== '' || email.value=='')
{
alert('fields Empty');
}
else
{
UpdateRecord();
}
Try this to compare values:
if(name.value == '' || email.value == '')
{
alert('fields Empty');
}
else
{
UpdateRecord();
}
Related
I'm trying to validate an email form with jQuery, and it isn't working, here is the part of the code I think the problem is:
if (isValid == false) {
event.preventDefault();
}
I get the message that event is deprecated, what does this mean and how can I fix it?
EDIT (here's the whole code):
$("#contact_form").submit( evt => {
let isValid = true;
// validate the first name entry
const firstName = $("#first_name").val().trim();
if (firstName == "") {
$("#first_name").next().text("This field is required.");
isValid = false;
} else {
$("#first_name").next().text("");
}
$("#first_name").val(firstName);
// validate the last name entry
const lastName = $("#last_name").val().trim();
if (lastName == "") {
$("#last_name").next().text("This field is required.");
isValid = false;
} else {
$("#last_name").next().text("");
}
$("#last_name").val(lastName);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
Change event to evt.
if (!isValid)
{
evt.preventDefault();
}
The event you're trying to prevent is the one from the 'submit' listener. Not the global event.
$("#contact_form").submit( evt => { });
Im trying to clear only the password and confirm password fields when those are not matched.
Im calling a function when the submit button is pressed which contains a password checking condition. How should I clear only password and confirmpassword inputs if that condition is true?
function checkmatch()
{
var name = $("#username").val();
var address = $("#address").val();
var email = $("#emailid").val();
var mobile = $("#phonenum").val();
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
return false;
}
else if((name==null || name == "") || (address==null || address == "") || (email==null || email == "") || (mobile=null || mobile == "") || (password==null || password == "") || (cnfirmPassword==null || cnfirmPassword == ""))
{
alert("Please fill all the required fields.");
return false;
}
else
{
$.ajax(
{
type: "POST",
url: "assmt1.php",
datatype: "html",
data: $("#fm1").serialize(),
success: function(response)
{
}
});
alert("Your form has been submitted. Thank you!");
}
}
Is this what you mean?
var password = $("#newPwd").val();
var cnfirmPassword = $("#confirmPwd").val();
if(password != cnfirmPassword)
{
alert("Passwords do not match.");
$("#newPwd").val('').focus(); ///this will not focus because of alert
$("#confirmPwd").val('');
return false;
}
All you need to do is call the same function you used to get the value.
Just pass empty string to val() like so:
$("#newPwd").val('');
$("#confirmPwd").val('');
i am validating a form and then asking for the confiormation through javascript…
so on submit i have called two function name validate() & make_confirm()..
onsubmit="return(validate() && show_alert(this));"
by this i am partially able to call both function but confirmation part is not working fine i have to redirect it to another page while pressing OK but its not going please help me out
validate & make_sure() function is as like:
function validate() {
if(document.getElementById('cname').value == '')
{
alert('Please enter your name');
document.getElementById('cname').focus();
return false;
}
else if(document.getElementById('address').value == '')
{
alert('Please enter your address');
document.getElementById('address').focus();
return false;
}
else if(document.getElementById('city').value == '')
{
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if(document.getElementById('state').value == '')
{
alert('Please enter your state');
document.getElementById('state').focus();
return false;
}
function make_sure() {
if(confirm("Do you really want to do this?"))
document.forms[0].submit();
else
return false;
}
Use one function for validate and confirm and set action of form to redirect form current page to another page.
function validateAndConfirm() {
if( isEmpty(id('cname').value) ) {
alert('Please enter your name');
id('cname').focus();
return false;
}
else if( isEmpty(id('address').value) ) {
alert('Please enter your address');
id('address').focus();
return false;
}
else if( isEmpty(id('city').value) ) {
alert('Please choose your city');
document.getElementById('city').focus();
return false;
}
else if( isEmpty(id('state').value) ) {
alert('Please enter your state');
id('state').focus();
return false;
} else {
if(confirm("Do you really want to do this?")) {
document.forms[0].submit();
}
else {
return false;
}
}
}
function isEmpty(val){
return (typeof val == 'undefined' || val === undefined || val == null || val.length <= 0) ? true : false;
}
// this function help to simplify you writing : document.getElementById to just id
function id(sid){
return document.getElementById(sid);
}
Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.
Markup:
<input type="text" name="email" />
Code:
$(':text').focusout(function(){
$(this).validate(function(){
$(this).attr('name');
});
});
Plugin:
(function($){
$.fn.validate = function(type) {
return this.each(function(type) {
if (type == 'email') {
matches = this.val().match('/.+#.+\..{2,7}/');
(matches != null) ? alert('valid') : alert('invalid');
}
/*else if (type == 'name') {
}
else if (type == 'age') {
}
else if (type == 'text') {
}*/
else {
alert('total failure');
}
});
};
})(jQuery);
The problem is that when I execute the code above, it runs the plugin as if type was a string: "function(){
$(this).attr('name');
});" instead of executing it as a function. How do I solve this?
You must check if the parameter is a function. If yes use the return value else assume it's a literal value.
(function($) {
$.fn.validate = function(type) {
//check if type type is a function else take it as literal
type = typeof type !== "function" ? type : type();
return this.each(function(type) {
...
});
};
})(jQuery);