jQuery validation not working when input fields are empty - javascript

I think this is not complex one but I can't do it by myself. I am very thankful for your help.
I am going to submit a form with validation. It seems like my validations are not working properly. Because when the input fields are empty it's not showing an error message. And also when clicking the submit button it's not showing error message. This incident only happens when input fields are empty.
Here is my HTML:
<form name="department" id="department">
<div class="form-group">
<label for="example-text-input">Department Name</label>
<span id="errfnCustomer"></span>
<input class="form-control" type="text" placeholder="Enter Department Name" id="textDepartmentName" name="textDepartmentName1">
</div>
<div class="form-group">
<label for="example-text-input">Registation Number</label>
<span id="errfnCustomer2"></span>
<input class="form-control" type="text" placeholder="Enter Department Registation Number" id="textRegistationNumber" name="textRegistationNumber">
</div>
<div class="form-group">
<label for="example-text-input">Web Site</label>
<input class="form-control" type="text" placeholder="Web Site" id="textWebsite" name="textWebsite1">
</div>
<div class="form-actions">
<div class="form-group">
<input type="button" value="Register" class="btn pull-right" id="btnsubmit" style="background-color:#1e90ff; width: 100px; color: white; font-weight: bold" />
</div>
</div>
</div>
And jQuery:
$('#department').validate({
rules: {
textDepartmentName1: {
required: true,
minlength: 3,
},
textRegistationNumber: {
required: true,
minlength: 3
},
textWebsite1: {
required: true,
minlength: 3
}
},
submitHandler: $("#btnsubmit").click(function (form) {
var submitData = {
DepartmentId: saveStat,
DepartmentName: $('#textDepartmentName').val().trim(),
RegistationNumber: $('#textRegistationNumber').val(),
Website: $('#textWebsite').val(),
Email: $('#textEmail').val(),
Telephone01: $('#textTelephone01').val(),
Telephone02: $('#textTelephone02').val(),
Fax: $('#textFax').val(),
BranchId: $('#cmbGetBranch').val()
}
if (saveStat == 0) {
$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
type: 'POST',
data: "{submitData:" + JSON.stringify(submitData) + "}",
url: "/Department/AddDepartment",
success: function (saveDepartment) {
if (saveDepartment.saveDepartment.DepartmentId != 0) {
refresh();
alert(saveDepartment.saveDepartment.DepartmentName + " Saved succesfully...!!!");
} else {
alert('warning' + " Department saving unsucsessful...!!!");
}
},
error: function (xhr, errorThrown) {
alert('Error...!!! Internal - 01');
}
});
} else {
$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
type: 'POST',
data: "{submitData:" + JSON.stringify(submitData) + "}",
url: "/Department/UpdateDepartment",
success: function (updateDepartment) {
if (updateDepartment.updateDepartment.DepartmentId != "") {
alert(updateDepartment.updateDepartment.DepartmentName + " updated succesfully...!!!");
refresh();
} else {
alert("Department update error...!!!");
}
},
error: function (xhr, errorThrown) {
alert('Error...!!!');
}
});
}
grid();
})
});

First of all make register buttom type submit:
<input type="submit" value="Register" class="btn pull-right" id="btnsubmit" style="background-color:#1e90ff; width: 100px; color: white; font-weight: bold" />
And make submit handler something like this:
submitHandler:function (form) {
}
See more here (Jquery validation).

Related

How to work that JavaScript_button in mustache template?

{{#stocks}}
<tr>
<td>{{client}}</td>
<td>{{productName}}</td>
<td>{{color}}</td>
<td>{{size}}</td>
<td>{{amount}}</td>
<td>
<form>
<div class="form-group">
<input type="text" id="addAmount" class="form-control">
</div>
<div style="display:none" class="form-group">
<input type="text" id="id" class="form-control" value="{{id}}" style="display:none">
</div>
</form>
</td>
<td>
<button type="button" class="btn btn-secondary" id="btn-addAmount">add</button>
</td>
</tr>
{{/stocks}}
this is my web_server project mustache template part
var addAmount = {
init: function () {
var _this = this;
$('#btn-addAmount').on('click', function () {
_this.addAmount();
})
},
addAmount: function () {
var data = {
id: $('#id').val(),
addAmount: $('#addAmount').val()
}
if(!data.addAmount) {
alert("input amount");
}
else {
$.ajax({
type: 'POST',
url: '/api/v1/addAmount',
dataType: 'json',
contentType: 'application/json; charset = utf-8',
data: JSON.stringify(data)
}).done(function() {
window.location.href = "/users/stock";
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
}
};
addAmount.init();
this is javascript button in my web_server project mustache template
When I run this code at this situation, only the first items button works. I want to make other buttons work too. Please tell me how to solve this problem.

Email input value come undefined on alert using javascript

I have form which contain email input field
<form id="TypeValidation" action="" method="post" enctype='multipart/form-data'>
<div class="form-group has-label col-sm-6">
<label>
Email
</label>
<input class="form-control" name=email" type="email" required>
</div>
<div class="card-footer text-center">
<button type="submit" name="add_usr_acc" id="add_usr_acc" value="add_usr_acc" class="btn btn-primary" >Add</button>
</div>
</div>
</form>
Issue is that in script code when alert on email then come undefined. how to get value in which user type a email
<script>
$("#TypeValidation").on('submit', (function(e) {
var email = $(this).find('input[name="email"]').val();
alert(email); {
e.preventDefault();
$.ajax({
url: "fn_acc_submit.php?addUsraccID=" + addUsraccID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "html",
beforeSend: function() {
$("#add_usr_acc").prop('disabled', 'disabled')
},
success: function(result) {
alert(result);
location.reload();
if (result == '1') {
location.replace("lst_user_account.php");
} else {
location.replace("add_user_account.php");
}
}
});
}
}));
</script>
Please fix my problem where I am doing wrong.
Problem is in your HTML code at below line:
<input class="form-control" name=email" type="email" required>
Here name=email" is not valid.
Change this to name="email"
In you input field, it should name="email". You forgot to add opening quotes.

Receiving array form data as JSON sent by jQuery and received by Node Js

I am playing around with Node Js and I have been building an app as a learning process, in this app I want to send data from a HTML form via a jQuery/AJAX and have Node Js/Express receive and process the data.
HTML is below with a series of these input groups:
<form action="/nodeRoute" method="post" id="myFormID">
<div class="input-group col-xs-4">
<input type="text" class="form-control input-sm" name="field1[]" />
<span class="input-group-addon">-</span>
<input type="text" class="form-control input-sm" name="field2[]" />
</div>
</form>
On the jQuery end I am sending the data like so:
$('#myFormID').submit(function(event) {
event.preventDefault();
var formData = $('#myFormID').serializeArray();
// Send AJAX request.
$.ajax({
type: "POST",
url: "/nodeRoute",
data: JSON.stringify({formData}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log('Success');
},
failure: function(err) {
console.log("Failure", err);
}
});
});
On the node end I am using router.use(bodyParser.json()); and outputting console.log(req.body.formData);. What I get is the below:
[ { name: 'field1[]', value: '12' },
{ name: 'field1[]', value: '34' },
{ name: 'field2[]', value: '56' },
{ name: 'field2[]', value: '78' } ]
What I would like is:
[ { field1: [12,34], field2: [56,78] } ]
Is this possible?
To build the data in the format you require you would need to do it manually by looping through the elements of the form and setting the keys and values in an object. Try this:
var formData = {};
$('#myFormID .form-control').each(function() {
var fieldName = this.name.replace(/\[\]/g, '');
if (!formData[fieldName])
formData[fieldName] = [];
formData[fieldName].push(this.value);
});
console.log(formData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/nodeRoute" method="post" id="myFormID">
<div class="input-group col-xs-4">
<input type="text" class="form-control input-sm" name="field1[]" value="12" />
<span class="input-group-addon">-</span>
<input type="text" class="form-control input-sm" name="field2[]" value="34" />
</div>
<div class="input-group col-xs-4">
<input type="text" class="form-control input-sm" name="field1[]" value="56" />
<span class="input-group-addon">-</span>
<input type="text" class="form-control input-sm" name="field2[]" value="78" />
</div>
</form>
From there you can just provide the resulting object to the data property of $.ajax. You don't need to stringify it as jQuery will do that for you:
// Send AJAX request.
$.ajax({
type: "POST",
url: "/nodeRoute",
data: formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log('Success');
},
failure: function(err) {
console.log("Failure", err);
}
});
This is how I would do it:
// your node backend
req.body.field.split(' '); // => [ 12, 32, ... ]
<!-- your html -->
<input type="text" name="field">

How to send similar data in array using JSON and AJAX Post Method using jQuery

HTML CODE
<form id="details">
<div>
<input type="text" placeholder="Email ID" id="email"></input>
<input type="text" placeholder="Mobile Number" id="mobile"></input>
</div>
<h5>Data</h5>
<div>
<div>
<input type="text" placeholder="Name" id="name1"></input>
<input type="text" placeholder="Age" id="age1"></input>
</div>
<div>
<input type="text" placeholder="Name" id="name2"></input>
<input type="text" placeholder="Age" id="age2"></input>
</div>
</div>
</form>
JS CODE
$(document).ready(function() {
$("form").on('submit', function(e) {
// Prepare data
var form = $("form");
var formData = new FormData(document.getElementById("details"));
e.preventDefault();
$.ajax(form.attr('action'), {
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: "json",
success: function(result) {
// Success Code
},
error: function(result) {
// Failure Code
},
timeout: 5000,
});
});
});
The codepen link for my code is http://codepen.io/anon/pen/VKzGRG
I want to send data like
{
"email" : "xyz#gmail.com",
"mobile" : "9898989898",
"data" : [
{
"name":"xyz",
"age":45
},
{
"name":"xyz",
"age":45
}
]
}
I tried sending the data using jQuery.
The problem is that it's sending only one name and age.
Also, in my project, I'm dynamically adding a Name and Age box using jQuery and a button.
How can I send the data using AJAX post method using jQuery?
you have missed the name of input that's why data is not posting
see the below working code.
//HTML code
<form name="details" action="t.php" id="details">
<div>
<input type="text" name="email" placeholder="Email ID" id="email"></input>
<input type="text" name="mobile" placeholder="Mobile Number" id="mobile"></input>
</div>
<h5>Data</h5>
<div>
<div>
<input type="text" name="data1[]" placeholder="Name" id="name1"></input>
<input type="text" name="data1[]" placeholder="Age" id="age1"></input>
</div>
<div>
<input type="text" name="data2[]" placeholder="Name" id="name2"></input>
<input type="text" name="data2[]" placeholder="Age" id="age2"></input>
</div>
</div>
<input type="submit" value="send">
</form>
//ajax code
$(document).ready(function() {
$("form").on('submit', function(e) {
// Prepare data
var form = $("form");
var formData = new FormData(document.getElementById("details"));
console.log(formData);
e.preventDefault();
$.ajax(form.attr('action'), {
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: "json",
success: function(result) {
// Success Code
},
error: function(result) {
// Failure Code
},
timeout: 5000,
});
});
});
To post data with jQuery and Ajax, you can do something like this
var myObj = {
"email" : "xyz#gmail.com",
"mobile" : "9898989898",
"data" : [
{
"name":"xyz",
"age":45
},
{
"name":"xyz",
"age":45
}
]
};
$.post( "test.php", myObj)
.done(function( data ) {
alert( "Data Loaded: " + data );
});
That will post the data and alert the response of the request.

jquery validation plugin ajax submit a form not working

I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is working but ajax code will do two time and the form cannot send out.
bootstrap form
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic</label>
<input class="form-control" type="text" name="topic" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label "> ruser: </label>
<input class="form-control" type="text" name="ruser" value="<?php echo $username; ?>" readonly/>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
<button class="btn btn-success" id="submitcontact">ok</button>
</form>
javascript
$(document).ready(function () {
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages: {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter nuser'
},
content: {
required: 'enter content'
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function (msg) {
alert("ok!");
if (msg == 'ok') {
alert(msg);
location.reload()
}
},
error: function () {
alert("failure");
}
});
return false;
}
});
$('#submitcontact').click(function () {
$('form.contact').submit();
})
});
How can i fix the problem?
The jsfiddle
You probably need to remove this bit:
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Please see the example:
http://jsfiddle.net/8eoreedb/1/
Use .valid() method:
Description: Checks whether the selected form is valid or whether all selected elements are valid.
Updated Fiddle
$('#submitcontact').on('click', function() {
if ($('form.contact').valid()) {
// Form is valid
$('form.contact').submit();
}
});
Doc: http://jqueryvalidation.org/valid/
Demo: http://jsfiddle.net/8eoreedb/4/

Categories

Resources