I'm using the clone method to duplicate a form. I'm adding and removing the active
class on the buttons but, once I clone the form, the duplicate buttons no longer
function because they share the same class as the original. I want the buttons to still
function regardless how many times I clone it. I used jQuery and JavaScript, and I'm
still new to programming. Can you please give me some ideas as to how to solve this.
Thanks in advance fellow developers.
Here is my HTML Code:
<div class="column-bottom phone">
<p class="para_txt">Phone</p>
<div id="main-wrapper">
<div id="wrapper_1" class="parentClass">
<div class="basic_infor">
<p>Select the nature of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_first_4 " >Private</button>
<button class="func_btns btn_second_4" >Work</button>
</div>
</div>
<div class="basic_infor">
<p>Select the type of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_5">Mobile</button>
<button class="func_btns btn_6 ">Telephone</button>
<button class="func_btns btn_7 ">Fax</button>
<button class="func_btns btn_8">Extension</button>
</div>
</div>
<div class="txt_area">
<input type="textarea" placeholder="+27 85 223 5258">
<span onclick="delete_el();">x</span>
</div>
</div>
</div>
<div class="btn_add">
<button class="repl_btns phone_repl" onclick="duplicate();">Add additional</button>
<p>Display on foreman contact list?</p>
<input type="checkbox" id="input_field" name="Phone_contact">
</div>
</div>
Here is my jQuery and JavaScript Code. I selected the class for the first button and
added a active class to it while removing the active class for the second button. I did
the same for the rest of the buttons.
//private btn
$(".btn_first_4").click(function () {
$(this).addClass("is_active");
$(".btn_second_4").removeClass("is_active");
});
//work btn
$(".btn_second_4").click(function () {
$(this).addClass("is_active");
$(".btn_first_4").removeClass("is_active");
});
//Bottom 5 btns
$(".btn_5").click(function () {
$(this).addClass("is_active");
$(".btn_6,.btn_7,.btn_8").removeClass("is_active");
})
$(".btn_6").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_7,.btn_8").removeClass("is_active");
})
$(".btn_7").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_8").removeClass("is_active");
})
$(".btn_8").click(function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_7").removeClass("is_active");
})
/*
Cloning Functions....
I tried to set the id of my new clone to "wrapper_2", but it only works when i clone it
once. I wanted to change the class attribute this way but I realize it wont work as
well. Please advise. Thanks
*/
function duplicate(){
const wrapper = document.getElementById("wrapper_1");
const clone = wrapper.cloneNode(true);
clone.id = "wrapper_2";
const main_wrapper = document.getElementById("main-wrapper");
main_wrapper.appendChild(clone)
}
function delete_el() {
const del_el = document.getElementById("wrapper_2");
del_el.remove();
}
Problems
If you use .cloneNode() any event handlers bound to the original will not carry over to the clone. Fortunately you are using jQuery which has it's own method .clone(). It has the ability to clone and keep event handlers, $(selector).clone(true) to copy with events and $(selector).clone(true, true) for a deep copy with events.
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
.clone()|jQuery API Documentation
Do not clone anything with an id, in fact you are using jQuery so don't use id at all. Convert every id to a class, it might feel like a lot of work but in the long run you'll be thankful you did.
Do not use inline event handlers
<button onclick="lame(this)">DON'T DO THIS</button>
This is especially important if you use jQuery which makes event handling incredibly easy to write and very versatile.
let count = 0;
$('output').val(++count);
$('.remove').hide();
$('.select button').on('click', function() {
const $old = $(this).parent().find('.active');
if (!$old.is(this)) {
$old.removeClass('active');
}
$(this).toggleClass('active');
});
$('.clear').on('click', function() {
$(this).parent().find('input').val('');
});
$('.remove').on('click', function() {
$(this).closest('.fields').remove();
let out = $.makeArray($('output'));
count = out.reduce((sum, cur, idx) => {
cur.value = idx + 1;
sum = idx + 1;
return sum;
}, 0);
});
$('.add').on('click', function() {
const $first = $('.fields').first();
const $copy = $first.clone(true, true);
$copy.insertAfter($('.fields').last());
$copy.find('output').val(++count);
$copy.find('.remove').show();
$copy.find('input').val('');
});
html {
font: 300 2ch/1.2 'Segoe UI'
}
fieldset {
min-width: fit-content
}
.fields {
margin-top: 1rem;
}
output {
font-weight: 900;
}
menu {
display: flex;
align-items: center;
margin: 0.5rem 0 0.25rem;
}
button,
input {
display: inline-block;
font: inherit;
font-size: 100%;
}
button {
cursor: pointer;
border: 1.5px ridge lightgrey;
}
.numbers {
display: flex;
align-items: center;
margin: 1rem 0 0.5rem -40px;
}
.clear {
border: 0;
font-size: 1.25rem;
line-height: 1.25;
}
.right {
justify-content: flex-end;
}
.left {
padding-left: 0;
}
.number-3 {
width: 9rem;
}
.number-1 {
width: 3rem;
}
[class^="number-"] {
font-family: Consolas
}
.clear {
border: 0;
background: transparent;
}
label+label {
margin-left: 6px;
}
button:first-of-type {
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
button:nth-of-type(2) {
border-radius: 0;
}
button:last-of-type {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.active {
outline: 2px lightblue solid;
outline-offset: -2px;
}
#foreman {
transform: translate(0, 1.5px)
}
.btn.remove {
display: block;
border-radius: 4px;
float: right;
}
<form id='phone'>
<fieldset class='main'>
<legend>Add Phone Numbers</legend>
<section class='fields'>
<fieldset>
<legend>Phone Number <output value='1'></output></legend>
<button class='btn remove' type='button'>Remove</button>
<label>Phone number is used for:</label>
<menu class='purpose select'>
<button class="btn priv" type='button'>Private</button>
<button class="btn work" type='button'>Work</button>
</menu>
<label>Select the type of phone:</label>
<menu class='type select'>
<button class="btn mob" type='button'>Mobile</button>
<button class="btn tel" type='button'>Telephone</button>
<button class="btn fax" type='button'>Fax</button>
</menu>
<menu class='numbers'>
<form name='numbers'>
<label>Number:  </label>
<input name='phone' class='number-3' type="tel" placeholder="+27 85 223 5258" required>
<label>  Ext.  </label>
<input name='ext' class='number-1' type='number' placeholder='327'>
<button class='btn clear' type='button'>X</button>
</form>
</menu>
</fieldset>
</section>
<fieldset>
<menu class='right'>
<button class='btn cancel' type='button'>Cancel</button>
<button class='btn done'>Done</button>
<button class='btn add' type='button'>Add</button>
</menu>
</fieldset>
<footer>
<menu>
<input id='foreman' name="contact" type="checkbox">
<label for='foreman'>Display on foreman contact list?</label>
</menu>
</footer>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
When load page , JS add event click for elements ( elements were created)
When you clone new elements ( those do not add event click) and event click of you not working on those elements
You are using Jquery then i suggest you code same as below :
$(document).on('click', ".btn_first_4", function () {
$(this).addClass("is_active");
$(".btn_second_4").removeClass("is_active");
});
//work btn
$(document).on('click', ".btn_second_4", function () {
$(this).addClass("is_active");
$(".btn_first_4").removeClass("is_active");
});
//Bottom 5 btns
$(document).on('click', ".btn_5", function () {
$(this).addClass("is_active");
$(".btn_6,.btn_7,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_6", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_7,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_7", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_8").removeClass("is_active");
})
$(document).on('click', ".btn_8", function () {
$(this).addClass("is_active");
$(".btn_5,.btn_6,.btn_7").removeClass("is_active");
})
function duplicate(){
const wrapper = document.getElementById("wrapper_1");
const clone = wrapper.cloneNode(true);
clone.id = "wrapper_2";
const main_wrapper = document.getElementById("main-wrapper");
main_wrapper.appendChild(clone)
}
function delete_el() {
const del_el = document.getElementById("wrapper_2");
del_el.remove();
}
.is_active {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column-bottom phone">
<p class="para_txt">Phone</p>
<div id="main-wrapper">
<div id="wrapper_1" class="parentClass">
<div class="basic_infor">
<p>Select the nature of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_first_4 " >Private</button>
<button class="func_btns btn_second_4" >Work</button>
</div>
</div>
<div class="basic_infor">
<p>Select the type of phone:</p>
<div class="parent_btns">
<button class="func_btns btn_5">Mobile</button>
<button class="func_btns btn_6 ">Telephone</button>
<button class="func_btns btn_7 ">Fax</button>
<button class="func_btns btn_8">Extension</button>
</div>
</div>
<div class="txt_area">
<input type="textarea" placeholder="+27 85 223 5258">
<span onclick="delete_el();">x</span>
</div>
</div>
</div>
<div class="btn_add">
<button class="repl_btns phone_repl" onclick="duplicate();">Add additional</button>
<p>Display on foreman contact list?</p>
<input type="checkbox" id="input_field" name="Phone_contact">
</div>
</div>
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.