Send errors from Javascript using Html form - javascript

I'm trying to collect errors from js and send to email, but I'm not receving any email upon form submission. Here's my code:
<form id="vm-user-form" class="pure-form pure-form-aligned vm-user-form form-horizontal">
<div class="vm-modal-body">
<h4>Please provide us with these details.</h4>
<fieldset class="form-group">
<!-- <div class="pure-control-group"> -->
<label for="username">Name:</label>
<input id="vm-username" class="pure-input-1" name="username" type="text" placeholder="Your Names" pattern="[\w]{3,20}(\s)?[\w]{3,20}" title="eg. John Don" aria-required="true" required>
<!-- </div> -->
<!-- <div class="pure-control-group"> -->
<label for="phoneno">Phone Number:</label>
<input id="vm-phoneno" class="pure-input-1" name="phoneno" type="text" placeholder="Your Phone No." pattern="^(\+)?[\d]{6,14}$" title="eg. 0203001575, 023001575" aria-required="true" required>
<!-- </div> -->
<!-- <div class="pure-control-group"> -->
<label for="email">Email Address:</label>
<input id="vm-email" class="pure-input-1" name="emailaddress" type="email" placeholder="example-name#gmail.com" aria-required="true" required>
<!-- </div> -->
<!-- <div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary">Submit</button>
</div> -->
</fieldset>
</div>
<div class="vm-modal-footer">
<!-- <div class="pure-controls"> -->
<button type="button" class="vm-close-form hide pure-button button-danger" data-dismiss="modal">Close</button>
<button type="submit" id="vm-submit-btn" class="pure-button button-vm">Submit</button>
<!-- </div> -->
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</form>
Below is the Javascript code that is supposed to work with the Html code.
JavaScript:
var politeErrorResponse = function(reason) {
var waitToLoad = setTimeout(function() {
// Save the details for later use
status.reason = reason;
// Load up the form
$('.vm-popup-form').on('hidden.bs.modal', function(e) {
// do something...
// $('.vm-popup-form').modal('toggle');
// alert("previous modal hidden.");
$(".vm-close-form").show(300).addClass("hide").next().show(300);
});
$('.vm-popup').parent().load(chrome.extension.getURL('resources/view/form.html'), function() {
$('.vm-popup-form').modal('toggle')
$("#vm-user-form").on("submit", function(event) {
// prevent default form submit
event.preventDefault();
if ($('#vm-username').attr('value') != "" && $('#vm-phoneno').attr('value') != "" && $('#vm-email').attr('value') !== "") {
// reason carries the following:
// reason = ["caught", "isPostFunction", "responseText", "part_html"];
// On ERROR collect these DATA
var errorDetails = {
"username": $('#vm-username').attr('value'),
"phoneno": $('#vm-phoneno').attr('value'),
"emailaddress": $('#vm-email').attr('value')
}
// add this data to reason
$.extend(true, errorDetails, status.reason);
console.log(errorDetails);
$('.vitumob-popup-form .vm-modal-body').html(function() {
// Submit the details and error, and return Response
submitErrors(errorDetails, errorDetails.isPostFunction);
$(".vm-close-form").hide(300).removeClass("hide").next().fadeToggle().prev().show(300).on("click", function() {
// $('.vm-modal').modal("hide");
document.getElementById("vitumob-user-form").submit();
});
return '<h2> Your order has been submitted. We shall contact you. Thank you.</h2>'
})
} else {
// Focus on the 1st input
$('#vm-username').focus();
}
});
// alert("triggered the loading of the form");
});
}, 3000);
// Cancel the submission of the form
}
Please Help.

Related

Hidden input not submitted after updating value in on submit event

Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.

jQuery validate plugin working only on last shown div [duplicate]

This question already exists:
jQuery show/hide form with jQuery validate plugin working on last shown div only
Closed 4 years ago.
I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.
Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown.
Below is the first div with no validation messages
Below is the second div with no validation messages
Here is my form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zootopia</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
</head>
<body>
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
Here is my JavaScript:
$(document).ready(function(){
$("#ad_section2").click(function(){
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
$("#ad_form").validate({
rules:{
ad_title:{
required: true
},
description:{
required: true
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title"
},
description: {
required: "please enter a description"
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
})
Here is my CSS:
#ad_form_section2,
#ad_form_section3{
display: none;
}
You need to add a condition before you show/hide next fields
if ( $('field-id').valid() ) {
// Code
}
For example:
$("#ad_section2").click(function(){
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:
<meta charset="UTF-8">
Form Example:
$(document).ready(function(){
$("#ad_form").validate({
rules:{
ad_title:{
required: true,
minlength: 3, // set minimum title length
},
description:{
required: true,
minlength: 10,
},
location:{
required: true
}
},
messages:{
ad_title: {
required: "please enter an ad title",
minlength: "Your title must be more than 3 characters!",
},
description: {
required: "please enter a description",
minlength: "Your description must be at least 10 characters long",
},
location: {
required: "please enter a location"
}
},
submitHandler: function(form) {
var petID = $( "#pet_ad option:selected" ).val();
var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;
$(form).ajaxSubmit({
url:addAdUrl,
type:"post",
datatype: 'json',
success: function(result){
if(result.petAd == false){
alert("Pet ad already exists!");
}else{
alert("Ad posted!");
$('#image_table').hide();
}
},
error: function(error) {
alert("Error");
}
});
}
});
$("#ad_section2").click(function(){
// Check if valid before show/hide
if ($('#ad_title').valid() && $('#description').valid()) {
$("#ad_form_section1").hide();
$("#ad_form_section2").show();
}
});
$("#back_section1").click(function(){
$("#ad_form_section1").show();
$("#ad_form_section2").hide();
});
$("#ad_section3").click(function(){
// Check if valid before show/hide
if ($('#location_ad').valid()) {
$("#ad_form_section3").show();
$("#ad_form_section2").hide();
}
});
$("#back_section2").click(function(){
$("#ad_form_section2").show();
$("#ad_form_section3").hide();
});
});
#ad_form_section2,
#ad_form_section3 {
display: none;
}
label.error {
color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="container">
<form id="ad_form" method="post">
<div id="ad_form_section1">
<div class="form-group">
<label for="ad_title">Ad Title</label>
<input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
</div>
<div class="form-group">
<label for="description">Describe what you're offering</label>
<textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
</div>
<button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section2">
<div class="form-group">
<label for="location"> Location</label>
<input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
</div>
<button type="button" id="back_section1" class="btn btn-primary"> Back </button>
<button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
</div>
<div id="ad_form_section3">
<div>
<label> Select pet pictures</label>
<input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
</div>
<button type="button" id="back_section2" class="btn btn-primary"> Back </button>
<input type="hidden" name="action_type" value="add" />
<input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
</div>
</form>
</div>
More examples from documentation
By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".
$("#ad_form").validate({
ignore: [], // ignore nothing, validate everything
rules:{
ad_title:{ ....
If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.
However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.
Here's one example:
https://stackoverflow.com/a/20481497/594235

Second callback does not work

I call postAjax on button click, which calls signupUser, this works fine, but then I want signupUser to call showWelcomeMessage which for some reason it doesn't work. I get no error in the console but ´no success message shows up in the HTML´. I am also thinking that maybe the way I am targeting the html is not correct ( and there is no problem with the callback itself ) and that´s why I do not see any message.
NOTE: The sSuccessMessage should show up on the LOGIN page (html div), cause after succesfull signup, SIGNUP page ( html div ) gets hidden and LOGIN shows up.
Please help me find what´s wrong.
// GLOBAL ARRAY for storing any DATA from the SERVER
var ajDataFromServer = [];
/************************************************************************/
/************************************************************************/
/************************************************************************/
// Main ajax function using callback for posting data to the server
function postAjax( sUrl , frmData, callback ){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var ajDataFromServer = JSON.parse(this.responseText);
callback( ajDataFromServer, showSuccessMessage );
}
}
ajax.open( "POST", sUrl , true );
var jFrm = new FormData( frmData );
ajax.send( jFrm )
}
// DO the SIGNUP, POST data to the SERVER with AJAX
btnSignupForm.addEventListener("click", function (e) {
//var lblErrorMessage = e.target.parentNode.nextSibling.contains.classList("lblErrorMessage");
postAjax("api_signup_users.php", frmSignup, signupUser);
});
function signupUser( ajUserDataFromServer, showSuccessMessage ) {
if ( ajUserDataFromServer.status == "ok" ) {
//console.log( "SIGNUP SUCCESFULL" );
pageLogin.style.display = "flex";
pageSignup.style.display = "none";
showSuccessMessage( "Account succesfully created - Signup please" );
} else {
//console.log( "SIGNUP FAIL - TRY AGAIN" );
pageViewProducts.style.display = "none";
pageLogin.style.display = "none";
pageSignup.style.display = "flex";
lblSignupErrorMessage.innerHTML = "";
var sSignupErrorMessage = "Signup Failed - Try again";
lblSignupErrorMessage.insertAdjacentHTML( 'beforeend', sSignupErrorMessage );
}
}
/************************************************************************/
/************************************************************************/
/************************************************************************/
function showSuccessMessage ( sSuccessMessage ) {
var lblErrorMessage = document.querySelector(".lblErrorMessage");
lblErrorMessage.innerHTML = "";
var sSuccessMessage = sSuccessMessage.fontcolor( "#549839" );
lblErrorMessage.insertAdjacentHTML('beforeend', sSuccessMessage);
}
Here is the HTML part:
<!-- SIGNUP for USERS and ADMIN -->
<div id="pageSignup" class="page popup">
<div class="wrapper">
<h3>SIGNUP</h3>
<form class="form" id="frmSignup">
<input type="text" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
<input type="text" name="txtName" placeholder="Name" required>
<input type="text" name="txtLastName" placeholder="Lastname" required>
<input type="password" name="txtPassword" placeholder="Password" required>
<div class="lblFileUpload">
<p>Select your picture:</p>
<input type="file" name="fileUserImage" required>
</div>
<button type="button" class="btnForm" id="btnSignupForm">Signup</button>
<div class="lblFormExtention">
<p class="pyesAccount">Already have an account?</p>
<button type="button" class="btnShowPage" id="btnLogin" data-showThisPage="pageLogin">Login</button>
</div>
</form>
<h3 class="lblErrorMessage" id="lblSignupErrorMessage"></h3>
</div>
</div>
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- LOGIN for USERS and ADMIN -->
<div id="pageLogin" class="page popup">
<div class="wrapper">
<h3>LOGIN</h3>
<form class="form" id="frmLogin">
<input type="text" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
<input type="text" name="txtPassword" placeholder="Password" required>
<button type="button" class="btnForm" id="btnLoginForm">Login</button>
<div class="lblFormExtention">
<p class="pnoAccount">Don´t have an account?</p>
<button type="button" class="btnShowPage" id="btnSignup">Signup</button>
</div>
</form>
<h3 class="lblErrorMessage" id="lblLoginErrorMessage"></h3>
</div>
</div>
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- SUBSCRIBE for USERS -->
<div id="pageSubscribe" class="page popup">
<div class="wrapper">
<h3>SUBSCRIBE TO OUR NEWSLETTER</h3>
<form class="form" id="frmSubscribe">
<input type="text" name="txtEmail" placeholder="Email" required>
<input type="text" name="txtName" placeholder="Name" required>
<input type="text" name="txtLastName" placeholder="Lastname" required>
<input type="text" name="txtAddress" placeholder="Address" required>
<div id="mapinForm">
<!-- Generated dynamically -->
</div>
<button type="button" class="btnForm" id="btnSubscribeForm">Subscribe</button>
</form>
<h3 class="lblErrorMessage" id="lblSubscribeErrorMessage"></h3>
</div>
</div>
When you query element via document.querySelector(".lblErrorMessage") you get your first element of that class which is <h3 class="lblErrorMessage" id="lblSignupErrorMessage"></h3> and it's hidden at the time you call showSuccessMessage().
You probably need to query element by its ID, using document.getElementById()
Update:
If you don't want to query each element by ID, your solution will be to update every .lblErrorMessage element:
function showSuccessMessage ( sSuccessMessage ) {
Array.prototype.forEach.call(document.querySelectorAll(".lblErrorMessage"), function (el) {
el.innerHTML = "";
el.insertAdjacentHTML('beforeend', sSuccessMessage.fontcolor( "#549839" ));
// or simply use the following form:
// el.innerHTML = sSuccessMessage.fontcolor( "#549839" );
});
}
It works this way, however I am not sure if this is the most optimal way.
function showSuccessMessage ( sSuccessMessage ) {
var alblMessages = document.getElementsByClassName( "lblMessage" );
for ( var i = 0; i < alblMessages.length; i++ ) {
alblMessages[i].insertAdjacentHTML('beforeend', sSuccessMessage.fontcolor( "#549839" ));
}
}

Required field validation on group of text box Not working

I want to apply required field validation on text box group in which at least one text box group must contain value.
in bellow image, details of at least one bank must be filled.
I have used jquery-form-validator plugin from http://www.formvalidator.net/#custom-validators and created custome validator as bellow, but Its not working.
$("#txtBankDetails")
.valAttr('error-msg', 'select atlest 1 bankname.');
$.formUtils.addValidator({
name: 'data-text-group',
validatorFunction: function (value, $el, config, language, $form) {
debugger
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('data-text-group'),
// get checkboxes and count the checked ones
$textBoxes = $('input[type=textbox][data-text-group^="' + elname + '"]', $form),
nonEmptyCount = $textBoxes.filter(function () {
return !!this.value;
}).length;
alert(nonEmptyCount);
if (nonEmptyCount == 0) {
isValid = false;
}
}
});
// Setup form validation only on the form having id "registration"
$.validate({
form: '#registration',
modules: 'date, security, file, logic',
validateOnBlur: true,
showHelpOnFocus: true,
addSuggestions: true,
onModulesLoaded: function () {
console.log('All modules loaded!');
},
onSuccess: function ($form) {
form.submit();
alert("sucess")
return false;
},
onError: function () {
alert("Error")
}
});
html code is,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/theme-default.min.css"
rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="registration" method="post" action="#Url.Action("NewRegistration", "StaticPage")" enctype="multipart/form-data" class='has-validation-callback'>
<div class="container">
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname1" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankACNo1" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankAddress1" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname2" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input name="BankACNo2" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress2" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname3" data-text-group="BankName" placeholder="03. BANK NAME" >
</div>
<div class="col-md-4">
<input name="BankACNo3" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress3" placeholder="BANK ADDRESS">
</div>
</div>
</div>
<input value="PROCESS & PRINT" class="green-btn uppercase" type="submit" id="btnSubmit" />
</form>

Uncaught TypeError: Cannot read property 'val' of null jquery

I'm trying to pass form values, check them and then return the response with jquery, everything gets passed correctly, the image gets uploaded and the path gets added to the database, but instead of returning the message on the same page, it redirects to the addmember.php, doesn't even go through the checks - like the javascript file doesn't even exist and it has been bothering me for quite a while... I've tried searching but I didn't find anything relatable to me since the problem lies in the picture/image...
Uncaught TypeError: Cannot read property 'val' of null
addmember.js and the **form
$(document).ready(function() {
$("#submit").click(function() {
var membershipnumber = $("#membershipnumber").val();
var membername = $("#membername").val();
var membersurname = $("#membersurname").val();
var memberdate = $("#memberdate").val();
var memberphonenumber = $("#memberphonenumber").val();
var memberemail = $("#memberemail").val();
var memberpicture = document.getElementById("#memberpicture").val();
if ((membershipnumber == "") || (membername == "") || (membersurname == "") || (memberdate == "") || (memberphonenumber == "")) {
$("#message").html("<div class=\"alert alert-danger alert-dismissable fade in\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Polja označena sa * ne smeju biti prazna.</div>");
} else {
$.ajax({
type: "POST",
url: "addmember.php",
data: {
"membershipnumber": membershipnumber,
"membername": membername,
"membersurname": membersurname,
"memberdate": memberdate,
"memberphonenumber": memberphonenumber,
"memberemail": memberemail,
"memberpicture": memberpicture
},
success: function(html) {
var text = $(html).text();
var response = text.substr(text.length - 4);
$("#message").html(html);
},
error: function() {
},
beforeSend: function() {
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>")
}
});
}
return false;
});
});
<form name="createnewmember" id="createnewmember" method="post" action="addmember.php" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<!-- name and surname -->
<label for="membername" class="col-xs-2 control-label">Ime i prezime:<font color="#d9534f">*</font></label>
<div class="col-xs-10">
<div class="form-inline">
<input name="membername" id="membername" type="text" class="form-control" placeholder="Ime" autofocus />
<input name="membersurname" id="membersurname" type="text" class="form-control" placeholder="Prezime" />
</div>
</div>
</div>
<!-- /name and surname -->
<div class="form-group">
<!-- date of birth -->
<label for="memberdate" class="col-xs-2 control-label">Datum rođenja:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberdate" id="memberdate" type="date" class="form-control" value="1990-01-01" />
</div>
</div>
<!-- /date of birth -->
<div class="form-group">
<!-- membership number (scanned with barcode scanner) -->
<label for="membershipnumber" class="col-xs-2 control-label">Članski broj:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="membershipnumber" id="membershipnumber" type="text" class="form-control" placeholder="Članski broj" data-toggle="tooltip" data-placement="right" title="Očitajte bar-kod sa nekorišćene kartice." />
</div>
</div>
<!-- /membmership number -->
<div class="form-group">
<!-- phone number -->
<label for="memberphonenumber" class="col-xs-2 control-label">Broj telefona:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberphonenumber" id="memberphonenumber" type="text" class="form-control" placeholder="Broj telefona" />
</div>
</div>
<!-- /phone number -->
<div class="form-group">
<!-- email -->
<label for="memberemail" class="col-xs-2 control-label">Email adresa:</label>
<div class="col-xs-3">
<input name="memberemail" id="memberemail" type="text" class="form-control" placeholder="Email adresa" />
<div class="checkbox">
<label><input name="memberemailinglist" id="memberemailinglist" type="checkbox" disabled/> Prijavi na mailing listu?</label>
</div>
</div>
</div>
<!-- /email -->
<div class="form-group">
<!-- picture -->
<label for="memberpicture" class="col-xs-2 control-label">Slika:</label>
<div class="col-xs-10">
<label class="btn btn-default" for="memberpicture">
<input id="memberpicture" name="memberpicture" type="file" style="display:none;" onchange="$('#memberpicture-info').html($(this).val());" accept=".jpg,.png,.jpeg" class="form-control" />
<span class="glyphicon glyphicon-camera"></span> Traži...
</label>
<span class="label label-danger" id="memberpicture-info">Nije izabrana ni jedna slika...</span>
</div>
</div>
<!-- /picture -->
<div class="form-group">
<span class="pull-right">Polja označena sa <font color="#d9534f">*</font> su obavezna! &nbsp</span>
<!-- required fields text -->
</div>
<button name="Submit" id="submit" class="btn btn-default pull-right" type="submit">Podnesi</button>
<!-- submit button -->
</form>
<!-- /form -->
addmember.php
<?php
require 'includes/functions.php';
include_once 'config.php';
$membershipnumber = $_POST['membershipnumber'];
$membername = $_POST['membername']." ".$_POST['membersurname'];
$membersurname = $_POST['membersurname'];
$memberdate = $_POST['memberdate'];
$memberphonenumber = $_POST['memberphonenumber'];
$memberemail = $_POST['memberemail'];
$memberpicture_dir = '/images/members';
if(isset($_FILES['memberpicture'])) {
$memberpicture_temp = $_FILES['memberpicture']['tmp_name'];
$ext = pathinfo(basename($_FILES['memberpicture']['name']), PATHINFO_EXTENSION);
$memberpicture = $membershipnumber.".".$ext;
move_uploaded_file($memberpicture_temp , $_SERVER['DOCUMENT_ROOT'] . '/spartangym/images/members/' . $memberpicture);
} else {
$memberpicture = "nopicture.jpg";
}
$regdate = new DateTime();
$memberregdate = $regdate->getTimestamp();
$memberexpires = $memberregdate + 2592000;
if (strlen($memberemail) > 0 && !filter_var($memberemail, FILTER_VALIDATE_EMAIL) == true) {
echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Email adresa nije validna.</div><div id="returnVal" style="display:none;">false</div>';
} else {
$a = new AddMemberForm;
$response = $a->createMember($membershipnumber, $membername, $memberdate, $memberphonenumber, $memberemail, $memberpicture, $memberregdate, $memberexpires);
if ($response == 'true') {
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Član '. $membername .' je uspešno dodat u bazu.</div><div id="returnVal" style="display:none;">true</div>';
} else {
mySqlErrors($response);
}
};
?>
Your problem is here
var memberpicture = document.getElementById("#memberpicture").val();
Native methods don't have val(), nor should you include the hash.
As val() is a jQuery method, you probably wanted to do
var memberpicture = $("#memberpicture").val();
The native alternative would be
var memberpicture = document.getElementById("memberpicture").value;
Your validation looks fine, but on-click you should use event.preventDefault() to keep the form from submitting and only allow the submission in the event of all fields being valid.
Usage here:
https://api.jquery.com/event.preventdefault/
at first check
before check
var membershipnumber = $("#membershipnumber").val();
after check
var membershipnumber='none object';
if(typeof($('#membershipnumber'))!="undefined")
{
membershipnumber= $('#membershipnumber').val();
}
alert(membershipnumber);

Categories