JavaScript client side validation is not working - javascript

I have designed a login page, but client side validation is not working. I have written JavaScript code for validation. And how to make email extension acceptance only particular comp id. ex: user#example.com. It should accept only example.com email id's. I have tried to to give extension: "example.com" in JavaScript validation, but it's not working.
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<meta charset="utf-8">
<!-- Font CSS (Via CDN) -->
<link rel='stylesheet' type='text/css' href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'>
<!-- Favicon -->
<link rel="shortcut icon" href="img/favicon.ico">
<!--Table container---->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/ValidationFormScript.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<nav class="navbar navbar-light" style="background-color: #e3f2fd;">
<!-- Navbar content -->
</nav>
<!---Body starts here---->
<body>
<br><br><br><br>
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-8 banner-sec">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<img class="img-fluid" src="img/logo.jpg" alt="First slide">
</div>
</div>
</div>
</div>
<div class="col-sm-12 col-md-4 login-sec">
<!---Break line after header ---->
<br />
<!--- Form starts here----->
<form class="login-form" method="" action="" id="admin-form">
<!---- Starts the User ID section--->
<div class="form-group">
<label for="exampleInputEmail" class="text-left"><span>User ID</span></label>
<span class="input-status" data-toggle="tooltip" data-placement="top" title="Input your email"></span>
<input type="email" class="form-control" id="email" name="email" placeholder="enter email">
</div>
<!---- Starts the Password section--->
<div class="form-group">
<label for="exampleInputPassword" class="text-left"><span>Password</span></label>
<span class="input-status" data-toggle="tooltip" data-placement="top" title="Input your password"></span>
<input type="password" class="form-control" name="password" id="password" placeholder="enter password">
</div>
<!---- Ends the Password section--->
<!---Submit button--->
<div class="form-group">
<button type="submit" class="btn btn-login float-right">Login</button>
</div>
</form>
</div>
</div>
</section>
<!----- Script for Validation----->
<!-- jQuery Validate Plugin-->
<script src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
"use strict";
// Init Theme Core
Core.init();
// Init Demo JS
Demo.init();
/* #custom validation method (smartCaptcha)
------------------------------------------------------------------ */
$.validator.methods.smartCaptcha = function(value, element, param) {
return value == param;
};
$("#admin-form").validate({
/* #validation states + elements
------------------------------------------- */
errorClass: "state-error",
validClass: "state-success",
errorElement: "em",
/* #validation rules
------------------------------------------ */
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
email: {
required: true,
email: true,
extension: ""
},
website: {
required: true,
url: true
},
language: {
required: true
},
upload1: {
required: true,
extension: "jpg|png|gif|jpeg|doc|docx|pdf|xls|rar|zip"
},
mobileos: {
required: true
},
comment: {
required: true,
minlength: 30
},
mobile_phone: {
require_from_group: [1, ".phone-group"]
},
home_phone: {
require_from_group: [1, ".phone-group"]
},
password: {
required: true,
},
repeatPassword: {
required: true,
minlength: 6,
maxlength: 16,
equalTo: '#password'
},
gender: {
required: true
},
languages: {
required: true
},
verification: {
required: true,
smartCaptcha: 19
},
applicant_age: {
required: true,
min: 16
},
licence_no: {
required: function(element) {
return $("#applicant_age").val() > 19;
}
},
child_name: {
required: "#parents:checked"
}
},
/* #validation error messages
---------------------------------------------- */
messages: {
firstname: {
required: 'Enter first name'
},
lastname: {
required: 'Enter last name'
},
useremail: {
required: 'Enter email address',
email: 'Enter a VALID email address'
},
website: {
required: 'Enter your website URL',
url: 'URL should start with - http://www'
},
language: {
required: 'Choose a language'
},
upload1: {
required: 'Please browse a file',
extension: 'File format not supported'
},
mobileos: {
required: 'Please select a mobile platform'
},
comment: {
required: 'Oops you forgot to comment',
minlength: 'Enter at least 30 characters or more'
},
mobile_phone: {
require_from_group: 'Fill at least a mobile contact'
},
home_phone: {
require_from_group: 'Fill at least a home contact'
},
password: {
required: 'Please enter a password'
},
repeatPassword: {
required: 'Please repeat the above password',
equalTo: 'Password mismatch detected'
},
gender: {
required: 'Please choose specie'
},
languages: {
required: 'Select laguages spoken'
},
verification: {
required: 'Please enter verification code',
smartCaptcha: 'Oops - enter a correct verification code'
},
applicant_age: {
required: 'Enter applicant age',
min: 'Must be 16 years and above'
},
licence_no: {
required: 'Enter licence number'
},
child_name: {
required: 'Please enter your childs name'
}
},
/* #validation highlighting + error placement
---------------------------------------------------- */
highlight: function(element, errorClass, validClass) {
$(element).closest('.field').addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.field').removeClass(errorClass).addClass(validClass);
},
errorPlacement: function(error, element) {
if (element.is(":radio") || element.is(":checkbox")) {
element.closest('.option-group').after(error);
} else {
error.insertAfter(element.parent());
}
}
});
// Cache several DOM elements
var pageHeader = $('.content-header').find('b');
var adminForm = $('.admin-form');
var options = adminForm.find('.option');
var switches = adminForm.find('.switch');
var buttons = adminForm.find('.button');
var Panel = adminForm.find('.panel');
// Form Skin Switcher
$('#skin-switcher a').on('click', function() {
var btnData = $(this).data('form-skin');
$('#skin-switcher a').removeClass('item-active');
$(this).addClass('item-active')
adminForm.each(function(i, e) {
var skins = 'theme-primary theme-info theme-success theme-warning theme-danger theme-alert theme-system theme-dark'
var panelSkins = 'panel-primary panel-info panel-success panel-warning panel-danger panel-alert panel-system panel-dark'
$(e).removeClass(skins).addClass('theme-' + btnData);
Panel.removeClass(panelSkins).addClass('panel-' + btnData);
pageHeader.removeClass().addClass('text-' + btnData);
});
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-' + btnData);
} else {
$(e).removeClass().addClass('option option-' + btnData);
}
});
// var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-round switch-' + btnData);
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-' + btnData);
} else {
$(ele).removeClass().addClass('switch switch-' + btnData);
}
}
});
buttons.removeClass().addClass('button btn-' + btnData);
});
setTimeout(function() {
adminForm.addClass('theme-primary');
Panel.addClass('panel-primary');
pageHeader.addClass('text-primary');
$(options).each(function(i, e) {
if ($(e).hasClass('block')) {
$(e).removeClass().addClass('block mt15 option option-primary');
} else {
$(e).removeClass().addClass('option option-primary');
}
});
// var sliders = $('.ui-timepicker-div', adminForm).find('.ui-slider');
$('body').find('.ui-slider').each(function(i, e) {
$(e).addClass('slider-primary');
});
$(switches).each(function(i, ele) {
if ($(ele).hasClass('switch-round')) {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-round switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-round switch-primary');
}
} else {
if ($(ele).hasClass('block')) {
$(ele).removeClass().addClass('block mt15 switch switch-primary');
} else {
$(ele).removeClass().addClass('switch switch-primary');
}
}
});
buttons.removeClass().addClass('button btn-primary');
}, 800);
});
</script>
</body>
</html>
<style type="text/css">
#import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
.login-block{
background: #fff; /* fallback for old browsers */
background: -webkit-linear-gradient(to bottom, #fff, #fff); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to bottom, #fff, #fff); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
float:left;
width:100%;
padding : 50px 0;
}
.banner-sec{background:#fff; no-repeat left bottom; background-size:cover; min-height:0px; border-radius: 0 10px 10px 0; padding:0;}
.carousel-inner{border-radius:10px 10px 10px 10px;}
}
.login-sec{padding: 60px 30px; position:relative;}
.login-sec .copy-text{position:absolute; width:100%; bottom:20px; font-size:13px; text-align:left;}
.login-sec .copy-text i{color:#FEB58A;}
.login-sec .copy-text a{color:#E36262;}
.login-sec h2{margin-bottom:30px; font-weight:400; font-size:30px; color: grey;}
.btn-login{background: #90EE90; color:#000; font-weight:400;}
.banner-text{width:70%; position:absolute; bottom:40px; padding-left:20px;}
.banner-text p{color:#fff;}
.carousel-caption {
position: absolute;
left: 3%;
right: 26%;
bottom: 160px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
font: Century Gothic;
font-weight: 400;
}
body {
font-family: "Helvetica Neue",Century Gothic,Century Gothic,Century Gothic;
font-size: 14px;
line-height: 1.428571429;
color: grey;
background-color: #fff;
}
.palel-primary
{
border-color: #bce8f1;
}
.panel-primary>.panel-heading
{
background:#bce8f1;
}
.panel-primary>.panel-body
{
background-color: #EDEDED;
}
input {
margin-top: 5px;
margin-bottom: 5px;
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
vertical-align:middle;
margin-left:20px
}
label {
display:inline-block;
*display: inline; /* for IE7*/
zoom:1; /* for IE7*/
float: left;
padding-top: 5px;
text-align: right;
width: 80px;
}
.form-control {
display: block;
width: 77%;
height: 32px;
}
.label{
color: black;
}
label span { color: black;
font-weight: normal !important;}
a {
text-decoration: none !important;
}
body {
margin-bottom:50px;
}
</style>
JavaScript code for validation, but it's not working.

You need to add an attribute called, 'pattern' (based on regular expressions). It should look like,
<input type="email" class="form-control" id="email" name="email" placeholder="enter email" pattern="[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+"/>
Optionally, you can also publish custom error messages using event handler attributes like oninput, onvalid,... It brings value and helpful to direct the users with more precise & meaningful messages.

If you are only going to use the email input to validate, it is better to use javascript to validate the input and show error messages.
function checkRegistration() {
var email = document.getElementById('login-email').value;
var alertMessage = document.getElementById('alert-email');
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var isValid = re.test(email);
if (isValid) {
alertMessage.innerHTML = '';
alertMessage.style.opacity = 0;
alertMessage.style.visibility = 'hidden';
} else {
alertMessage.innerHTML = "You have entered an invalid email address!";
alertMessage.style.opacity = 1;
alertMessage.style.visibility = 'visible';
}
return isValid;
}
#alert-email {
visibility:hidden;
opacity:0;
transition:visibility 0s linear,opacity 0.5s linear;
}
<form onsubmit="return checkRegistration()">
<div>
<label>User ID</label>
<input type="email" placeholder="enter email" id="login-email" />
</div>
<span id="alert-email"></span>
<div>
<label>Password</label>
<input type="password" placeholder="enter password" id="login-password" />
</div>
<button type="submit" class="btn btn-login float-right">Login</button>
</form>

Try to add new require for JQuery validate:
$.validator.addMethod("email_domain", function (value, element) {
var regex = /^[a-zA-Z0-9_.+-]+#(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(domain|domain2)\.com$/;
if(!regex.test(value)) {
return false;
}else{
return true;
}
});
Then add "email_domain" to form require validate

Related

HTML Form Doesn't Send Data through AJAX Post

I have a DataTable that uses AJAX to pull from 8 different SharePoint lists, and organizes them based on there Program attribute, then child row is organized by the Deliverable attribute, followed by the grandchild rows which is the remaining information about the "Deliverable". Everything about that aspect works perfectly for my DataTable.
However, I need to be able to write back information to this DataTable, so the easiest route I thought to take would to be a HTML form read the input, then post it to the corresponding SharePoint list based on its "Program" attribute. I have the form built under the DataTable and I cannot figure out how to get it to send to the SharePoint list. I am currently only using only one Program just to see if it works and I am unsuccessful. I tried to console.log() a few things and nothing showed up.
Here is a picture of my table and form.
Here is my code:
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
data = data;
var table = $('#myTable').DataTable();
table.rows.add( data.value ).draw();
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
} );
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
swal("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
var baseUrl = "http://WebAppURL"
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
'headers': { 'Accept': 'application/json;odata=nometadata' },
success: function (data) {
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"pageLength": 100,
"columns": [
{ "data": null, "defaultContent": "" },
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export or Update Table',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
{
text: 'Update Table',
action: function (e, dt, node, config){
$('#myModal').modal('show');
}
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success");
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
h1{
text-align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.modal-dialog-centered {
display:-webkit-box;
display:-ms-flexbox;
display:flex;
-webkit-box-align:center;
-ms-flex-align:center;
align-items:center;
min-height:calc(100% - (.5rem * 2));
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="heading">
<h1 class="center"><strong>Deliverables</strong></h1>
</div>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th></th>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update DataTable</h4>
</div>
<div class="modal-body">
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id = "dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "Yes">Yes</option>
<option value = "No">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn-submit" name="btn-submit" class="btn-submit" value="Submit" />
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Your Snippit contains error/warnings as following:
URL array binding which is string break on array child.
Undefined object used to bind, SharePoint Rest API data parameter in
Success method data.value is used while REST API returns JSON results as data.d.results.
Multiple document ready
baseUrl variable is not defined
Rest of all is good now but needs more code optimization.
Set baseUrl = "http://webappurl"; with your server/webappurl and try this snippit.
Try this snippit, Hope this can help you now.
So i made Test in my environment SP-OnPrem 2013 and using a Script Editor webpart.
Here is the result. I made two list with Deliverables and saved this in Test1Deliverable.
Oh Gosh, I thought it was oblivious that you can bind variables from input field values to insert them in SP list but you are assigning them as the name of the field in input html. so you need to replace this section of script
'Program': program,
'Deliverable': deliverable,
'To': to,
'Date': date,
'Approved': approved,
'Notes': notes
Replace with
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
Note: I gave Id to all the input and select elements and using their value to POST them into SP. After submit , just refresh the page or call loadData() again and in my case Notes1 and Date1 columns used.
In Case of My Script Editor Code:
<style type="text/css">
#myform {
margin:0 auto;
width:250px;
padding:14px;
align: center;
}
label {
width: 10em;
float: left;
margin-right: 0.5em;
display: block;
vertical-align: middle;
}
.submit {
float:right;
}
fieldset {
background:#EBF4FB none repeat scroll 0 0;
border:2px solid #B7DDF2;
width: 450px;
}
legend {
color: #fff;
background: #80D3E2;
border: 1px solid #781351;
padding: 2px 6px
text-align: center;
}
.elements {
padding:10px;
}
p {
border-bottom:1px solid #B7DDF2;
color:#666666;
font-size:12px;
margin-bottom:20px;
padding-bottom:10px;
}
span {
color:#666666;
font-size:12px;
margin-bottom:1px;
}
.btn{
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
color: #333333;
text-align: center;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
vertical-align: middle;
cursor: pointer;
background-color: #f5f5f5;
border: 1px solid #B7DDF2;
}
.btn:hover{
color: #333333;
background-color: #e6e6e6;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
.header {
padding: 10px;
text-align: center;
}
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.dt-button-collection {
position: static;
}
</style>
<link rel ="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.1.2/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<link rel ="stylesheet" href="https://cdn.datatables.net/rowgroup/1.1.2/css/rowGroup.bootstrap4.min.css"/>
<link rel ="stylsheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"/>
<link rel ="stylesheet" href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css"/>
<div class ="container">
<table id="myTable" class="table table-bordered" cellspacing="0" width="100%">
<thead class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</thead>
<tfoot class="thead-dark">
<tr>
<th>Program</th>
<th>Deliverable</th>
<th>To</th>
<th>Date</th>
<th>Approved</th>
<th>Notes</th>
</tr>
</tfoot>
</table>
<form id="myform" type="post">
<fieldset>
<legend align="center">Update Datatable</legend>
<p>Please fill out the shown fields to add data to the DataTable</p>
<div class="elements">
<label for="program">Program :</label>
<select name = "program" id="dProgram">
<option value = "AHR">AHR</option>
<option value = "AMMO">AMMO</option>
<option value = "DAR-Q">DAR-Q</option>
<option value = "Doctrine Development">Doctrine Development</option>
<option value = "Operational Energy">Operational Energy</option>
<option value = "Ordnance Multimedia">Ordnance Multimedia</option>
<option value = "SRC Handbook">SRC Handbook</option>
<option value = "WTBn">WTBn</option>
</select>
</div>
<div class="elements">
<label for="Deliverable">Deliverable :</label>
<select name="Deliverable" id="dDeliverable">
<option value = "Meeting Minutes">Meeting Minutes</option>
<option value = "Monthly Status Report (MSR)">Monthly Status Report (MSR)</option>
</select>
</div>
<div class="elements">
<label for="To"> To:</label>
<input type="text" align= "center" id="dTo" name="to" placeholder="example#example.com">
</div>
<div class="elements">
<label for="Date">Date: </label>
<input type="date" align= "center" id="dDate" name="date" placeholder="MM/DD/YYYY">
</div>
<div class="elements">
<label for="Approved">Approved :</label>
<select name="Approved" id="dApproved">
<option value = "True">Yes</option>
<option value = "False">No</option></select>
</div>
<div class="elements">
<label for="Notes"> Notes :</label>
<input type="text" align= "left" id="dNotes" name="notes" placeholder="Please provide notes">
</div>
<div class="submit">
<input type="submit" id="btn" name="btn" class="btn" value="Submit" />
</div>
</fieldset>
</form>
<script type="text/javascript">
var baseUrl = "http://webappurl";
function loadData() { //Initializing the AJAX Request function to load in the external list data from different subsites
//create an array of urls to run through the ajax request instead of having to do multiple AJAX Requests
var urls = [baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('Dar-Q Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
"baseUrl + "_api/web/lists/getbytitle('WTBn Deliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('ODMultiDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('OEDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('DocDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('AHRDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable",
"baseUrl + "_api/web/lists/getbytitle('SRCDeliverables')/items?$select=Program,To,Date,Approved,Notes,Deliverable"];
for (i=0; i < urls.length; i++) { //for loop to run through the AJAX until all URLs have been reached
$.ajax({
url: urls[i],
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) { // success function which will then execute "GETTING" the data to post it to a object array (data.value)
console.log(data);
if(data.d != null && data.d != undefined && data.d.results.length> 0){
var table = $('#myTable').DataTable();
table.rows.add(data.d.results).draw();
}
}
});
}
}
$(document).ready(function() {
var collapsedGroups = {};
var top = '';
var parent = '';
var table = $('#myTable').DataTable( {
"columns": [
{ "data": "Program", visible: false },
{ "data": "Deliverable", visible: false },
{ "data": "To" },
{ "data": "Date" },
{ "data": "Approved" },
{ "data": "Notes" }
],
dom: "<'row'<'col-sm-12 col-md-10'f><'col-sm-12 col-md-2'B>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
buttons: [{
extend: 'collection',
className: "btn-dark",
text: 'Export',
buttons:
[{
extend: "excel", className: "btn-dark"
},
{
extend: "pdf", className: "btn-dark"
},
{
extend: "print", className: "btn-dark"
},
],
}],
order: [[0, 'asc'], [1, 'asc'] ],
rowGroup: {
dataSrc: [
'Program',
'Deliverable'
],
startRender: function (rows,group,level){
var all;
if (level === 0) {
top = group;
all = group;
} else if (level === 1) {
parent = top + group;
all = parent;
// if parent collapsed, nothing to do
if (!collapsedGroups[top]) {
return;
}
} else {
// if parent collapsed, nothing to do
if (!collapsedGroups[parent]) {
return;
}
all = top + parent + group;
}
var collapsed = !collapsedGroups[all];
console.log('collapsed:', collapsed);
rows.nodes().each(function(r) {
r.style.display = collapsed ? 'none' : '';
});
//Add category name to the <tr>.
return $('<tr/>')
.append('<td colspan="8">' + group + ' (' + rows.count() + ')</td>')
.attr('data-name', all)
.toggleClass('collapsed', collapsed);
}
}
} );
loadData();
$('#myTable tbody').on('click', 'tr.dtrg-start', function () {
var name = $(this).data('name');
collapsedGroups[name] = !collapsedGroups[name];
table.draw(false);
});
});
$(document).ready(function() {
$("#btn").click(function(e){
var jsonData = {};
var formData = $("#myform").serializeArray();
// console.log(formData);
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
console.log(jsonData);
$.ajax({
async: true, // Async by default is set to “true” load the script asynchronously
// URL to post data into sharepoint list or your own url
url: baseUrl + "_api/web/lists/getbytitle('AMMO Deliverables')/items?$select=Program,Deliverable,To,Date,Approved,Notes",
method: "POST", //Specifies the operation to create the list item
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.AMMO_x0020_DeliverablesListItem' // it defines the ListEnitityTypeName
},
//Pass the parameters
'Program': $("#dProgram").val(),
'Deliverable':$("#dDeliverable").val(),
'To': $("#dTo").val(),
'Date': $("#dDate").val(),
'Approved': $("#dApproved").val(),
'Notes': $("#dNotes").val()
}),
headers: {
"accept": "application/json;odata=verbose", //It defines the Data format
"content-type": "application/json;odata=verbose", //It defines the content type as JSON
"X-RequestDigest": $("#__REQUESTDIGEST").val() //It gets the digest value
},
success: function(data) {
alert("Item created successfully", "success"); // Used sweet alert for success message
},
error: function(error) {
console.log(JSON.stringify(error));
}
})
});
});
</script>
</div>
You do not need to much of script, best way to submit form by onsubmit method using return false. You can use Jquery post method for this.

Jquery validation error displayed on "label". How to fix it?

My form is made using the “bootstrap” styles. To check for input fields, I use “jquery” validation. Label with the name is on top of input, when you click on input, “label” moves over “input”. When you click “Next”, the error “validation” appears on top of the “label” with the name, and should be located under the “input”. How to fix so that “label” moves above “input” and the error is below “input”?
my code
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
</script>
<style type="text/css">
#step2,#step3,#step4,#step5{
display: none;
}
.form-group label
{
position: absolute;
top: 3px;
pointer-events: none;
left: 20px;
transition: .5s;
}
.container .form-group input:focus ~label,
.container .form-group input:valid ~label
{
left: 20px;
top: -20px;
color: rgb(66,133,244);
font-size: 12px;
font-weight: bold;
}
</style>
<script>
$(document).ready(function(e){
$.validator.addMethod("minlenghtname", function (value, element) {
return /^[a-z]+$/i.test(value);
}," does not match the format");
$.validator.addMethod("requiredname", function (value, element) {
return value.length > 2;
}," fill this field");
var v = $("#commentForm").validate({
rules: {
fname: {
requiredname: true,
minlenghtname: true
},
lname: {
requiredname: true,
minlenghtname: true
}
},
submitHandler: function() {
alert("Submitted, thanks!");
}
})
$(".next1").click(function() {
if (v.form()) {
$("#step2").show();
$("#step1").hide();
$("#progressText").html("Step 2 of 4");
}
});
});
</script>
</head>
<body>
<div class="container">
<div id="progressText" style="margin-bottom:20px;">Step 1 of 4</div>
<form class="cmxform" id="commentForm" method="get" action="">
<div id="step1">
<div class="row">
<div class="form-group col-md-6 col-sm-6">
<input class="form-control" id="fname" name="fname" required="">
<label>First Name:</label>
</div>
<div class="form-group col-md-6 col-sm-6">
<input class="form-control" id="lname" name="lname" required="">
<label>Last Name:</label>
</div>
<p class="buttonWrapper">
<input name="formNext1" type="button" class="next1 nextbutton" value="Next" alt="Next" title="Next">
</p>
</div>
</div>
<div id="step2">
Next
</div>
</form>
</div>
</body>
</html>
Validation also uses labels to show errors so you end up with double label for each field. Those from validation come with error class, so you can target them and either show it normally:
.form-group label.error {
position: static;
}
or treat it like that label but move down:
.form-group label.error {
top: 35px;
}

Why i am not able to submit the form?

i am working on payment gateway, in that when i try to submit form with jquery it doesn't submit the form $('#checkout_form').submit(); here is my whole code for that
braintree.client.create({
authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
if($('#nonce').val() == '') {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return false;
}
$('#nonce').val(payload.nonce);
$('#checkout_form').submit();
return true;
});
} else {
return true;
}
});
});
});
body {
background-color: #fff;
}
.panel {
width: 80%;
margin: 2em auto;
}
.bootstrap-basic {
background: white;
}
.panel-body {
width: 90%;
margin: 2em auto;
}
.helper-text {
color: #8A6D3B;
font-size: 12px;
margin-top: 5px;
height: 12px;
display: block;
}
/* Braintree Hosted Fields styling classes*/
.braintree-hosted-fields-focused {
border: 1px solid #0275d8;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);
}
.braintree-hosted-fields-focused.focused-invalid {
border: 1px solid #ebcccc;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(100,100,0,.6);
}
#media (max-width: 670px) {
.btn {
white-space: normal;
}
}
<script src="https://js.braintreegateway.com/web/3.36.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.36.0/js/hosted-fields.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<div class="panel panel-default bootstrap-basic">
<div class="panel-heading">
<h3 class="panel-title">Enter Card Details</h3>
</div>
<form class="panel-body" action="checkout.php" method="post" id="checkout_form">
<div class="row">
<div class="form-group col-sm-8">
<label class="control-label">Card Number</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="card-number"></div>
<span class="helper-text"></span>
</div>
<div class="form-group col-sm-4">
<div class="row">
<label class="control-label col-xs-12">Expiration Date</label>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-month"></div>
</div>
<div class="col-xs-6">
<!-- Hosted Fields div container -->
<div class="form-control" id="expiration-year"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-sm-6">
<label class="control-label">Security Code</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="cvv"></div>
</div>
<div class="form-group col-sm-6">
<label class="control-label">Zipcode</label>
<!-- Hosted Fields div container -->
<div class="form-control" id="postal-code"></div>
</div>
</div>
<input type="hidden" name="payment_method_nonce" id="nonce">
<button type="submit" value="submit" id="submit" class="btn btn-success btn-lg center-block">Pay with <span id="card-type">Card</span></button>
</form>
</div>
Can anyone please help to resolve this issue ?

Zebra Datepicker not showing validation error message

I'm using the Zebra Datepicker in one of my forms and I'm trying to validate it with the jzaefferer validate plugin. I want the input field to get a red border and I want a error message beneath the input field. The red border is working, but the error message isn't showing. How can I get the error message to show up?
This is my code (the error message should go into .diverror):
<div class="input-datepicker">
<label>Van:</label>
<input type="text" name="Datum1" class="datepicker" />
</div>
<div class="diverror"></div>
Zebra Datepicker places the <input> inside a <span> and adds a <button> under the <input> inside the <span>.
<div class="input-datepicker">
<label>Van:</label>
<span class="Zebra_DatePicker_Icon_Wrapper" style="display: block; position: relative; float: none; top: auto; right: auto; bottom: auto; left: auto;">
<input class="datepicker error" type="text" name="Datum1" readonly="readonly" style="position: relative; top: auto; right: auto; bottom: auto; left: auto;">
<button class="Zebra_DatePicker_Icon Zebra_DatePicker_Icon_Inside" type="button" style="top: 23px; left: 233px;">Pick a date</button>
</span>
</div>
<div class="diverror"></div>
I'm not that experienced with jquery but could it be the span that is messing up my appendTo in the example below.
Here's my validation.js:
$("#home-verhuur").validate({
errorPlacement: function(error, element) {
error.appendTo( element.parent("div").next("div") );
},
ignore: "input[type='text']:hidden",
onsubmit: true,
onkeyup: true,
onclick: true,
rules: {
Naam: {
required: true,
minlength: 2
},
Email: {
required: true,
email: true
},
Product: {
required: true
},
Personen: {
required: true,
min: 1
},
Datum1: {
required: true,
},
Datum2: {
required: true,
},
},
messages: {
Naam: "Vul je voornaam in (minimaal 2 karakters)",
Email: "Vul een correct Email adres in",
Product: "Kies een product",
Personen: "Vul het aantal personen in",
Datum1: "Kies een begindatum",
Datum2: "Kies een einddatum",
}
});
All the help is welcome!
Given your rendered HTML as constructed by the DOM...
You must change .parent() to .parents(), since the target div is now another level higher...
errorPlacement: function (error, element) {
error.appendTo(element.parents("div").next("div"));
},
DEMO: http://jsfiddle.net/2g953/1/

Two modal windows from yui example

I would like to have two buttons to open each one a diferent modal window with diferente content.
I am using this example from yui: http://yuilibrary.com/yui/docs/panel/panel-form-example.html
Things i try that did not work:
1. trying to duplicate the code
1. trying to duplicate the code and naming each div with a diferent name . Eg.:
Add and Add 1
and
This is the code from the example:
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?3.12.0/build/cssreset/reset-min.css&3.12.0/build/cssfonts/fonts-min.css&3.12.0/build/cssbase/base-min.css">
<script src="http://yui.yahooapis.com/3.12.0/build/yui/yui-min.js"></script>
<div id="dt"></div>
<p><button id="addRow">Add</button></p>
<div id="panelContent">
<div class="yui3-widget-bd">
</div>
</div>
<div id="nestedPanel"></div>
<script type="text/javascript">
YUI().use('datatable-mutable', 'panel', 'dd-plugin', function (Y) {
// Create the datatable with some gadget information.
var idField = Y.one('#productId'),
nameField = Y.one('#name'),
priceField = Y.one('#price'),
addRowBtn = Y.one('#addRow'),
cols = ['id', 'name', 'price'],
data = [
{id:'ga-3475', name:'gadget', price:'$6.99'},
{id:'sp-9980', name:'sprocket', price:'$3.75'},
{id:'wi-0650', name:'widget', price:'$4.25'}
],
dt, panel, nestedPanel;
// Define the addItem function - this will be called when 'Add Item' is
// pressed on the modal form.
function addItem() {
dt.addRow({
id : idField.get('value'),
name : nameField.get('value'),
price: priceField.get('value')
});
idField.set('value', '');
nameField.set('value', '');
priceField.set('value', '');
panel.hide();
}
// Create the main modal form.
panel = new Y.Panel({
srcNode : '#panelContent',
headerContent: 'Add A New Product',
width : 250,
zIndex : 5,
centered : true,
modal : true,
visible : false,
render : true,
plugins : [Y.Plugin.Drag]
});
// When the addRowBtn is pressed, show the modal form.
addRowBtn.on('click', function (e) {
panel.show();
});
});
</script>
Thank's in advance
I just work out in an example wich works :
<!DOCTYPE html>
<html lang="en" class="yui3-loading">
<head>
<meta charset="utf-8">
<title>Using a panel to show a modal form</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?3.12.0/build/cssreset/reset-min.css&3.12.0/build/cssfonts/fonts-min.css&3.12.0/build/cssbase/base-min.css">
<script src="http://yui.yahooapis.com/3.12.0/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<style type="text/css">
#desc {
margin-bottom: 20px;
border-bottom: 1px dotted #333;
}
#desc span {
background: #a3350d;
padding :2px;
color:# f27243;
}
.yui3-panel {
outline: none;
}
.yui3-panel-content .yui3-widget-hd {
font-weight: bold;
}
.yui3-panel-content .yui3-widget-bd {
padding: 15px;
}
.yui3-panel-content label {
margin-right: 30px;
}
.yui3-panel-content fieldset {
border: none;
padding: 0;
}
.yui3-panel-content input[type="text"] {
border: none;
border: 1px solid #ccc;
padding: 3px 7px;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
font-size: 100%;
width: 200px;
}
#addRow {
margin-top: 10px;
}
#dt {
margin-left: 1em;
}
#dt th, #dt td {
border: 0 none;
border-left: 1px solid #cbcbcb;
}
</style>
<h2>Using a panel to show a modal form</h2>
<div class="yui3-u-1">
<div id="dt"></div>
<p><button id="addRow">Add 1</button></p>
<p><button id="addRow2">Add 2</button></p>
<div id="panelContent">
<div class="yui3-widget-bd">
<form>
<fieldset>
<p>
<label for="id">ID</label><br/>
<input type="text" name="id" id="productId" placeholder="">
</p>
<p>
<label for="name">Name</label><br/>
<input type="text" name="name" id="name" value="" placeholder="">
</p>
<p>
<label for="password">Price</label><br/>
<input type="text" name="price" id="price" value="" placeholder="$">
</p>
</fieldset>
</form>
</div>
</div>
<div id="nestedPanel"></div>
<p></p>
<div id="panelContent2">
<div class="yui3-widget-bd">
<form>
<fieldset>
<p>
<label for="id">ID</label><br/>
<input type="text" name="id" id="productId" placeholder="">
</p>
<p>
<label for="name">Name</label><br/>
<input type="text" name="name" id="name" value="" placeholder="">
</p>
<p>
<label for="password">Price</label><br/>
<input type="text" name="price" id="price" value="" placeholder="$">
</p>
</fieldset>
</form>
</div>
</div>
<div id="nestedPanel2"></div>
</div>
<script type="text/javascript">
YUI().use('datatable-mutable', 'panel', 'dd-plugin', function (Y) {
// Create the datatable with some gadget information.
var idField = Y.one('#productId'),
nameField = Y.one('#name'),
priceField = Y.one('#price'),
addRowBtn = Y.one('#addRow'),
addRowBtn2 = Y.one('#addRow2'),
cols = ['id', 'name', 'price'],
data = [
{id:'ga-3475', name:'gadget', price:'$6.99'},
{id:'sp-9980', name:'sprocket', price:'$3.75'},
{id:'wi-0650', name:'widget', price:'$4.25'}
],
dt, panel, nestedPanel;
// Define the addItem function - this will be called when 'Add Item' is
// pressed on the modal form.
function addItem() {
dt.addRow({
id : idField.get('value'),
name : nameField.get('value'),
price: priceField.get('value')
});
idField.set('value', '');
nameField.set('value', '');
priceField.set('value', '');
panel.hide();
}
// Define the removeItems function - this will be called when
// 'Remove All Items' is pressed on the modal form and is confirmed 'yes'
// by the nested panel.
function removeItems() {
dt.data.reset();
panel.hide();
}
// Instantiate the nested panel if it doesn't exist, otherwise just show it.
function removeAllItemsConfirm() {
if (nestedPanel) {
return nestedPanel.show();
}
nestedPanel = new Y.Panel({
bodyContent: 'Are you sure you want to remove all items?',
width : 400,
zIndex : 6,
centered : true,
modal : true,
render : '#nestedPanel',
buttons: [
{
value : 'Yes',
section: Y.WidgetStdMod.FOOTER,
action : function (e) {
e.preventDefault();
nestedPanel.hide();
panel.hide();
removeItems();
}
},
{
value : 'No',
section: Y.WidgetStdMod.FOOTER,
action : function (e) {
e.preventDefault();
nestedPanel.hide();
}
}
]
});
}
// Create the DataTable.
dt = new Y.DataTable({
columns: cols,
data : data,
summary: 'Price sheet for inventory parts',
caption: 'Price sheet for inventory parts',
render : '#dt'
});
// Create the main modal form.
panel = new Y.Panel({
srcNode : '#panelContent',
headerContent: 'Add A New Product',
width : 250,
zIndex : 5,
centered : true,
modal : true,
visible : false,
render : true,
plugins : [Y.Plugin.Drag]
});
panel.addButton({
value : 'Add Item',
section: Y.WidgetStdMod.FOOTER,
action : function (e) {
e.preventDefault();
addItem();
}
});
panel.addButton({
value : 'Remove All Items',
section: Y.WidgetStdMod.FOOTER,
action : function (e) {
e.preventDefault();
removeAllItemsConfirm();
}
});
// When the addRowBtn is pressed, show the modal form.
addRowBtn.on('click', function (e) {
panel.show();
});
//custom
// Create the main modal form.
panel2 = new Y.Panel({
srcNode : '#panelContent2',
headerContent: 'Add A New New Product',
width : 250,
zIndex : 5,
centered : true,
modal : true,
visible : false,
render : true,
plugins : [Y.Plugin.Drag]
});
// When the addRowBtn is pressed, show the modal form.
addRowBtn2.on('click', function (e) {
panel2.show();
});
});
</script>
</body>
</html>

Categories

Resources