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.
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