Cannot Get / nodeJS problem, why do I get this message? - javascript
Please help - I am getting Cannot Get / in my NodeJS application. Why do I get this message?
I know it was here, sorry, but I can't figure out why I get the message.
I tried everything that I could and I still don't get it.
.............
.............
.............
.............
.............
index.js
var express=require('express');
var filePersonData = require("fs")
var jsonData=require('./persons.json');
var parser = require("body-parser");
var jsonFile = "./persons.json"
var app=express();
app.use(parser.urlencoded({extended:true}));
app.use(parser.json());
app.use(express.static("./web"));
// WRITE TO FILE
function readPerson(){
var file = filePersonData.readFileSync(jsonFile, "utf-8");
var jsonDATA = JSON.parse(file);
return jsonDATA;
}
// WRITE NEW PERSON TO FILE
function addPerson(person){
var jsonDATA = readPerson();
jsonDATA.persons.push(person);
filePersonData.writeFileSync(jsonFile, JSON.stringify(jsonDATA));
}
// CHECK IF PERSON EXIST
function ifExist(newPerson){
var jsonDATA = readPerson();
for(var person of jsonDATA.persons){
if(person.name.toLowerCase() == newPerson.name.toLowerCase())
return true;
}
return false;
}
// post to web
app.post("/api/newPerson", function(request, response) {
var person =request.body;
if(ifExist(person)){
response.status(400);
}else{
response.status(201);
addPerson(person);
}
response.send();
});
app.get('/api/persons',(req,res)=>{
res.status(200);
var jsonDATA = readPerson();
res.send(JSON.stringify(jsonDATA));
});
// listening to port 3500
app.listen(3500,
()=>{console.log("Server is listening to port 3500")});
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<script>
function loadData() {
let optionList = document.getElementById('country').options;
let options = ["Afghanistan", "Åland Islands", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua
and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain"];
options.forEach(option =>
optionList.add(new Option(option, option)));
}
//Get the person info
function newPerson() {
var person = {
name: document.getElementById("name").value,
age: Number(document.getElementById("age").value),
isMale: Boolean(document.getElementById("isMale").checked),
country: document.getElementById("country").value
};
//Check validation
if (!validateParameters(person)) {
return;
}
//fetch : get the web
fetch(`/api/newPerson`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(person),
})
.then(res => {
if (res.status == 201) {
alert(person.name + " added successfully");
window.location = "/personsData.html";
} else if (res.status == 400) {
alert("ERROR: Name already exist");
}
})
.catch(err => console.log(`ERROR : ${err}`));
}
/*
* Validation : person input
* Check if person name between 3-15
* Check if person age betwen 0-120
*/
function validateParameters(person) {
if (person.name.length < 3 || person.name.length > 15) {
alert("The name : " + person.name + " must contain more that 3
latters and below 15 ");
return false;
}
if (person.age < 0 || person.age > 120 || person.age == "") {
alert("The age " + person.age + " is wrong neew to be between 1-
120");
return false;
}
return true;
}
</script>
</head>
<body onload="loadData()">
<div class="center">
<label style="font-size:30px;">Name:</label>
<input style="font-size:20px;" type="text" id="name" placeholder="Your
name..." />
</div>
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Age:</label>
<input style="font-size:20px;" type="number" id="age" placeholder="Your
age..." />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Is Male ? </label>
<input style="font-size:20px;" type="checkbox" id="isMale" />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Country:</label>
<select style="font-size:20px;" id="country" placeholder="Your
country...">
</div>
<div class="center">
</select>
<br/>
<br/>
<input onclick="newPerson()" type="submit" value="ADD"></input>
</div>
</body>
</html>
personsData.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 1500px;
width: 80%;
background-color: powderblue;
}
b.filds {
font-size: 30px;
color: rgb(99, 31, 189);
padding-right: 10px;
padding-left: 10px;
}
body {
color: rebeccapurple;
}
h1 {
text-decoration: underline;
}
</style>
<script>
//Add all persons to personView string and print the data to html page
function formatPersons(personList) {
var personView = "";
for (person of personList) {
personView += `<b class="filds">| Name:</b>
<b class="filds">${person.name}</b>,</b>
<b class="filds">| Age: </b>
<b class="filds"><b class="filds">${person.age}</b>,</b>
<b class="filds">| is Male: </b>
<b class="filds"><b class="filds">${person.isMale}</b>,</b>
<b class="filds">| Country: </b>
<b class="filds"><b class="filds">${person.country}</b>.</b>
<br\>`;
}
document.getElementById("body").innerHTML = personView;
}
//Load data from persons JSON
function getAllPersons() {
fetch(`/api/persons`)
.then(res => res.json())
.then(body => formatPersons(body.persons))
.catch(err => console.log(`Error: ${err}`));
}
</script>
</style>
</head>
<body onload="getAllPersons()">
<h1>Persons data</h1>
<div>
<p id="body"></p>
</div>
</body>
</html>
When you hit the express server, it searches for index.html for path "/" by default. In your case, you don't have both defined. you should be able to access both of your pages with localhost:port/form.html" and localhost:port/personsData.html.
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.
Upload files on folders in google drive based on form response
first of all I want to say I know almost nothing about javascript. I'm trying to develop a form with google app script where you can upload a file and it will automatically put it in a specific folder based on the response you enter in the form. For example, if I'm asking in the form which class you want to choose, and the user choose class "1", then the file will be uploaded in the "class 1" folder. With the help of the answers in this forum, I was able to create something that should work, but for some reason it is not. With my limited knowledge I'm not able to find the issue, even if this is a very easy fix, because as I said I don't know well Javascript. Some of the words in the code are in Italian, hope this is not a problem. This is my code, but for some reasons it is not working: function doGet(e) { return HtmlService.createHtmlOutputFromFile('form.html'); } function uploadFiles(form) { try { if(form.classi == "classe1") { var dropbox = "Classi prime"; } else if(form.classi == "classe2") { var dropbox = "Classi seconde"; } else if(form.classi == "classe3") { var dropbox = "Classi terze"; } else if(form.classi == "classe4") { var dropbox = "Classi quarte"; } else if(form.classi == "classe5") { var dropbox = "Classi quinte"; } var folder, folders = DriveApp.getFoldersByName(dropbox); if (folders.hasNext()) { folder = folders.next(); } else { folder = DriveApp.createFolder(dropbox); } var blob = form.myFile; var fileBlob = form.myFile; var fname = fileBlob.getName(); var newName = form.myLastName+form.myFirstName; // simple example // extract extension using RegEx // from http://stackoverflow.com/a/680982/1677912 var extensionfinder = /(?:\.([^.]+))?$/; var ext = extensionfinder(fname)[1]; fileBlob.setName(newName+'.'+ext); var file = folder.createFile(blob); file.setDescription("Caricato da " + form.myFirstName+form.myLastName); return "<p> Il tuo file è stato caricato correttamente, " + form.myFirstName + "!"; } catch (error) { return error.toString(); } } <!DOCTYPE html> <html> <head> <base target="_top"> <title>Caricamento file Liceo Augusto</title> <style> input[type=text], select, textarea { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; margin-top: 6px; margin-bottom: 16px; resize: vertical } input[type=submit] { background-color: #c72222; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; } input[type=submit]:hover { background-color: #6e1010; } .container { border-radius: 5px; background-color: #f2f2f2; padding: 20px; margin: auto; width: 70%; border: 3px solid black; } </style> </head> <body> <h1><center>Compila il modulo per inviare il tuo documento</center></h1> <div class="container"> <form id="uploadFilesForm"> <label for="classe">Seleziona la classe:</label> <select id="classi" name="classi"> <option value="classe1">1</option> <option value="classe2">2</option> <option value="classe3">3</option> <option value="classe4">4</option> <option value="classe5">5</option> </select> <label for="name">Nome:</label> <input type="text" id="fname" name="myFirstName" placeholder="Il tuo nome..."> <label for="lname">Cognome:</label> <input type="text" id="lname" name="myLastName" placeholder="Il tuo cognome..."> <input type="file" name="myFile"> <br><br> <center><input type="submit" value="Invia documento" onclick="this.value='Caricamento...'; google.script.run.withSuccessHandler(fileUploaded) .uploadFiles(this.parentNode); return false;" > </center> </form> </div> <script> function fileUploaded(status) { document.getElementById('myForm').style.display = 'none'; document.getElementById('output').innerHTML = status; } </script> </body> </html>
How do I edit or updated an array of Objects CRUD app dynamically?
I am working on a bookmark "collector" app that allows users save websites urls as a collection. I have created an array collectX in the localstorage to save each collections. However I am trying to edit and update each collections that have created on another HTML page. How can I do that? Here is what I have tried so far: //get form values // create an object of the form values //create an empty array //append object of the form values to the empty array //display array object values showCollection(); var getButton = document.getElementById('clickIt'); var collectionTitle = document.getElementById("title"); var collectionDescription = document.getElementById('describe') getButton.addEventListener('click', function(e){ e.preventDefault() var collections = { title: collectionTitle.value, description: collectionDescription.value, collectedWebsites:[] } let webCollections = localStorage.getItem('collectx'); if(webCollections == null){ var collectionObj = [] alert('storage is empty') } else{ collectionObj = JSON.parse(webCollections); } collectionObj.push(collections); localStorage.setItem("collectx", JSON.stringify(collectionObj)); showCollection() }); function showCollection(){ let webCollections = localStorage.getItem('collectx') if(webCollections == null){ var collectionObj = [] alert('storage is empty') } else{ collectionObj = JSON.parse(webCollections); } let html= '' var demos = document.getElementById('demo'); collectionObj.forEach(function(item, index){ html += `<div class="collects"> Title: ${item.title} <br> Description: ${item.description} </div>` }) demos.innerHTML = html } body{ background-color: #000; } .collects{ width: 150px; height: 100px; padding: 10px 5px 10px 5px; margin-right: 20px; border-radius: 10px; display: inline-block; background-color: #fff; } <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CollectX</title> <link rel="stylesheet" href="/style.css"> </head> <body> <form id="forms"> <input id="title" type="text" placeholder="Collection name"> <br> <br> <input id="describe" type="text" placeholder="Description"> <button id="clickIt"> Submit </button> </form> <div id="demo"> </div> <script src="/script.js"></script> </body> </html> Here is the link to the JSFiddle: https://jsfiddle.net/c3jgezwr/2/ P.S: I have tried to the method used on this page: https://www.xul.fr/javascript/parameters.php
Please take a look to this example CSS body { background-color: #000; } .collects { min-width: 150px; min-height: 100px; padding: 10px 5px 10px 5px; margin-right: 20px; border-radius: 10px; display: inline-block; background-color: #fff; overflow: hidden; } HTML <form name="form"> <div> <input name="title" placeholder="Title" /> </div> <div> <input name="describe" placeholder="Describe" /> </div> <div> <input name="links" placeholder="Add links separated by coma" /> </div> <div> <button type="submit">Submit</button> </div> </form> JS const form = document.forms.form; form.addEventListener("submit", submitHandler); function getData() { return JSON.parse(localStorage.getItem("collectx")) ?? []; } function submitHandler(event) { event.preventDefault(); const form = event.target; const formData = new FormData(event.target); const data = Object.fromEntries(formData); const currentData = getData(); localStorage.setItem("collectx", JSON.stringify([...currentData, data])); form.reset(); render(); } function render() { const collection = getData(); const entries = collection .map( ({ title, describe, links }) => ` <div class="collects"> <p>Title: ${title}</p> <p>Describe: ${describe}</p> <p>Links: ${links && links .split(",") .map((link) => `${link}`) .join("<br />")} </p> </div>` ) .join(""); document.querySelector("#root").innerHTML = ` <div> ${entries} </div> `; } render(); https://jsfiddle.net/m3ws94zo/2/ The idea is to add a input to enter links separated by coma. In a real solution, you probably will need to validate the urls
How do I add multiple entries in a list in JavaScript
I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too. "use strict"; var $ = function(id) { return document.getElementById(id); }; var tasks = []; var displayTaskList = function() { var list = ""; // if there are no tasks in tasks array, check storage if (tasks.length === 0) { // get tasks from storage or empty string if nothing in storage var storage = localStorage.getItem("tasks") || ""; // if not empty, convert to array and store in global tasks variable if (storage.length > 0) { tasks = storage.split("|"); } } // if there are tasks in array, sort and create tasks string if (tasks.length > 0) { tasks.sort(); list = tasks.join("\n"); } // display tasks string and set focus on task text box $("task_list").value = list; $("task").focus(); }; var addToTaskList = function() { var task = $("task"); if (task.value === "") { alert("Please enter a task."); } else { // add task to array and local storage tasks.push(task.value); localStorage.tasks = tasks.join("|"); // clear task text box and re-display tasks task.value = ""; displayTaskList(); } }; var clearTaskList = function() { tasks.length = 0; localStorage.tasks = ""; $("task_list").value = ""; $("task").focus(); }; window.onload = function() { $("add_task").onclick = addToTaskList; $("clear_tasks").onclick = clearTaskList; displayTaskList(); }; body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 100%; background-color: white; width: 700px; margin: 0 auto; border: 3px solid blue; padding: 0 2em 1em; } h1 { font-size: 150%; color: blue; margin-bottom: .5em; } label { float: left; width: 8em; } input { width: 22em; margin-right: 1em; margin-bottom: 1em; } #tasks { margin-top: 0; float: right; } <!DOCTYPE html> <html> <head> <title>Ch09 Task Manager</title> <link type="text/css" rel="stylesheet" href="task_list.css"> <script type="text/javascript" src="task_list.js"></script> </head> <body> <main> <h1>Task Manager</h1> <div id="tasks"> <span id="name"> </span>Tasks<br> <textarea id="task_list" rows="8" cols="50"></textarea> </div> <label for="task">Task</label><br> <input type="text" name="task" id="task"><br> <input type="button" name="add_task" id="add_task" value="Add Task"> <input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br> <input type="button" name="delete_task" id="delete_task" value="Delete Task"> <input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br> <input type="button" name="set_name" id="set_name" value="Set Name"> <input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br> </main> </body> </html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that. var tasks = []; var displayTaskList = function() { var list = ""; if (tasks.length === 0) { // if there are no tasks in tasks array, check storage var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage if (storage.length > 0) { tasks = storage.split("|"); } // if not empty, convert to array and store in global tasks variable } if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string tasks.sort(); list = tasks.join("\n"); } $("#task_list").val(list); // display tasks string and set focus on task text box $("#task").focus(); }; var addToTaskList = function() { var task = $("#task").val(); console.log(`entering addtotask list with task value = ${task}`); if (task === "") { alert("Please enter a task."); } else { if (task.indexOf(',') === -1) { tasks.push(task); // add task to array and local storage } else { const split = task.split(','); // 2 lines for readability split.forEach(atask => { tasks.push(atask); }); } localStorage.tasks = tasks.join("|"); $("#task").val(""); // clear task text box and re-display tasks displayTaskList(); } }; var clearTaskList = function() { tasks.length = 0; localStorage.tasks = ""; $("#task_list").val(""); $("#task").focus(); }; window.onload = function() { $("#add_task").on('click', function() { addToTaskList(); }); $("#clear_tasks").on('click', function() { clearTaskList(); }); displayTaskList(); }; body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 100%; background-color: white; width: 800px; margin: 0 auto; border: 3px solid blue; padding: 0 2em 1em; } h1 { font-size: 150%; color: blue; margin-bottom: .5em; } label { float: left; width: 8em; } input { width: 22em; margin-right: 1em; margin-bottom: 1em; } #tasks { margin-top: 0; float: right; } <body> <main> <h1>Task Manager</h1> <div id="tasks"> <span id="name"> </span>Tasks<br> <textarea id="task_list" rows="8" cols="50"></textarea> </div> <label for="task">Task</label><br> <input type="text" name="task" id="task"><br> <input type="button" name="add_task" id="add_task" value="Add Task"> <input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br> <input type="button" name="delete_task" id="delete_task" value="Delete Task"> <input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br> <input type="button" name="set_name" id="set_name" value="Set Name"> <input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br> </main> <script src="//code.jquery.com/jquery-3.4.1.min.js"></script> </body>
Validating function written in javaScript runs only once?
goal : is to validate this form. http://jsbin.com/buwejurexa/1/ Code is below Show the user all errors at once when he clicks Save Product button and errors at each step also. What is done: Wrote a validating function returnVal() which is nested inside another function called displayStorage. What works : As the page loads the user clicks the Save Product button and the validating function seems to be working first time. I can see the alert. The issue starts when: The user selects the Category and Products and sees Wattage. This time he decides to click on Save Product. Nothing happens. No Validations are displayed step by step. No errors in Console but got a error in JS Bin that (Line 253: Expected a conditional expression and instead saw an assignment. Line 258: Unreachable 'return' after 'return'.) My guess : a) my if and else statement is missing something. I tried calling it from different functions but no luck. b) The four buttons use Jquery. so I am guessing do I need to call javascript function returnVal() inside Jquery. How do I do that. I did reference the 4 buttons in my validating function. can some help me get the validations right. Thanks!! var wattage = { 'Artic King AEB': 100, 'Artic King ATMA': 200, 'Avanti Compact': 300, 'Bosch SS': 400, 'Bosch - SHXUC': 100, 'Asko DS': 200, 'Blomberg': 300, 'Amana': 400 }; var annualEnergy = 0; var dailyEnergyConsumed = 0; function populateProducts(category, products) { var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS'); var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana'); switch (category.value) { case 'refrigerators': products.options.length = 0; for (i = 0; i < refrigerators.length; i++) { createOption(products, refrigerators[i], refrigerators[i]); } break; case 'dishWasher': products.options.length = 0; for (i = 0; i < dishWasher.length; i++) { createOption(products, dishWasher[i], dishWasher[i]); } break; default: products.options.length = 0; break; } populateWattage(products); } function createOption(ddl, text, value) { var opt = document.createElement('option'); opt.value = value; opt.text = text; ddl.options.add(opt); } function populateWattage(product) { document.getElementById('wattage').innerText = wattage[product.value]; populateStorage(); } function setConsumption(hrs) { setConsumption(); } dailyEnergyConsumption = function(hrs) { dailyEnergyConsumed = 0; dailyEnergyConsumed = parseFloat(hrs * parseInt(document.getElementById('wattage').innerText) / 1000).toFixed(2); document.getElementById('dailyEnergyConsumptionVal').innerText = dailyEnergyConsumed + " kWh"; populateStorage(); }; annualEnergyConsumption = function(days) { annualEnergy = 0; var allYear = document.getElementById('allYear'); var halfYear = document.getElementById('halfYear'); var threeMonths = document.getElementById('threeMonths'); var oneMonth = document.getElementById('oneMonth'); if (allYear || days != 365) { annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2); document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh"; } else if (days == 182 && !halfYear) { annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2); document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh"; } else if (days == 90 && !threeMonths) { annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2); document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh"; } else if (days == 30 && !oneMonth) { annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2); document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh"; } populateStorage(); }; // code that shows which button is clicked. Green div below the 4 buttons $(document).ready(function() { $("#h1").click(function() { $("#onesSelected").show(); $("#threeSelected").hide(); $("#sixSelected").hide(); $("#twentyFourSelected").hide(); }); $("#h3").click(function() { $("#threeSelected").show(); $("#onesSelected").hide(); $("#sixSelected").hide(); $("#twentyFourSelected").hide(); }); $("#h6").click(function() { $("#sixSelected").show(); $("#onesSelected").hide(); $("#threeSelected").hide(); $("#twentyFourSelected").hide(); }); $("#h24").click(function() { $("#twentyFourSelected").show(); $("#onesSelected").hide(); $("#threeSelected").hide(); $("#sixSelected").hide(); }); }); function compareSetup() { var prodName = localStorage.getItem('productKey'); var energyName = parseInt(localStorage.getItem('energyKey'), 10); var useName = parseInt(localStorage.getItem('estimatedUse'), 10); return false; } function populateStorage() { var productBox = document.getElementById("products"); var productName = productBox.options[productBox.selectedIndex].text; localStorage.setItem('productKey', productName); localStorage.setItem('energyKey', document.getElementById("annualEnergyConsumption").innerHTML); //localStorage.setItem.querySelector('input[id="usageRadio"]:checked').value; //localStorage.setItem('usageRadio' + $(this).attr('id'), JSON.stringify({ checked: this.checked })); //localStorage.setItem('estimatedUse', document.getElementById("usageRadio")); // do other things if necessary } function displayStorage() { var displayProduct = document.getElementById("displayName"); var displayAnnual = document.getElementById("displayAnnual"); displayProduct.innerHTML = "Selected Product: " + localStorage.getItem('productKey'); displayProduct.style = "display:inline;"; displayAnnual.innerHTML = "Annual Consumption: " + localStorage.getItem('energyKey'); returnVal(); } //validation code starts here function returnVal() { //initialize the form elements starting from form name , category and product dropdown, daily use buttons and finally the radio buttons var energyForm = document.getElementsByName("energyForm")[0]; // drop downs var catDropdown = document.getElementById("dd1"); var prodDropdown = document.getElementById("products"); // call the 4 Daily use button var notLotButton = document.getElementById("h1"); var averageButton = document.getElementById("h3"); var lotButton = document.getElementById("h6"); var alwaysButton = document.getElementById("h24"); // radio button group var allYearRadio = document.getElementById("allYear"); var halfYearRadio = document.getElementById("halfYear"); var threeMonthsRadio = document.getElementById("threeMonths"); var oneMonthRadio = document.getElementById("oneMonth"); // var missingFields = false; var strFields = ""; if (catDropdown.selectedIndex === 0) { missingFields = true; strFields += "Select Category and the related Product \n"; catDropdown.focus(); } else { return true; } if ((!notLotButton.clicked) && (!averageButton.clicked) && (!lotButton.clicked) && (!alwaysButton.clicked)) { missingFields = true; strFields += "Select atleast one Estimated Daily Use option \n"; } else { return true; } if ((!allYearRadio.checked) && (!halfYearRadio.checked) && (!threeMonthsRadio.checked) && (!oneMonthRadio.checked)) { missingFields = true; strFields += "Select atleast one Estimated Yearly Use option \n"; } else { return true; } if (missingFields = true) { alert("Please provide the following fields before continuing: \n" + strFields); } return false; return true; } function resetForm() { document.getElementById("resetButton"); document.getElementById("energyForm").reset(); document.getElementById('products').value = "select"; //document.getElementById('select_value').selectedIndex = 3; } #leftColumn { width: 600px; float: left; } .placeholderText { font: bold 12px/30px Georgia, serif; } body { padding-left: 45px; } #annualEnergyConsumption { font: bold 25px arial, sans-serif; color: #00ff00; } #dailyEnergyConsumptionVal { font: bold 25px arial, sans-serif; color: #00ff00; } #annualCostOperation { font: bold 40px arial, sans-serif; color: #00ff00; } .dailyButInline { display: inline; } #wattage { position: absolute; left: 160px; top: 130px; font: bold 25px arial, sans-serif; color: #00ff00; } /* mouse over link */ button:hover { background-color: #b6b6b6; } #onesSelected { position: absolute; left: 53px; top: 246px; background-color: #00ff00; display: none; width: 99px; height: 5px; } #threeSelected { position: absolute; left: 156px; top: 246px; background-color: #00ff00; display: none; width: 99px; height: 5px; } #sixSelected { position: absolute; left: 259px; top: 246px; background-color: #00ff00; display: none; width: 99px; height: 5px; } #twentyFourSelected { position: absolute; left: 362px; top: 246px; background-color: #00ff00; display: none; width: 113px; height: 5px; } #store { cursor: pointer; } <h2>Annual Energy Consumption and Cost Calculator</h2> <form id="energyForm" onSubmit="return compareSetup()" action="" method="post"> <div id="leftColumn"> <div> <span class="placeholderText">Choose Category</span> <span> <select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required> <option value="select">Select-a-Category</option> <option value="refrigerators">Refrigerators</option> <option value="dishWasher">DishWasher</option> </select> </span> </br> <span class="placeholderText">Select a Product</span> <span> <select id="products" onchange="populateWattage(this)" required> <option value="select" selected>--------------------------</option> </select> </span> </div> <div> <span class="placeholderText">Wattage</span> <span id="wattage">0</span> </br> </br> </div> <div id="buttonBoundary"> <div class="placeholderText">Estimated Daily Use</div> <div class="dailyButInline"> <button type="button" id="h1" onclick="dailyEnergyConsumption(1)">Not a Lot</br>1 hour per day</button> </div> <div class="dailyButInline"> <button type="button" id="h3" onclick="dailyEnergyConsumption(3)">Average</br>3 hour per day</button> </div> <div class="dailyButInline"> <button type="button" id="h6" onclick="dailyEnergyConsumption(6)">A Lot</br>6 hour per day</button> </div> <div class="dailyButInline"> <button type="button" id="h24" onclick="dailyEnergyConsumption(24)">Always On</br>24 hours per day</button> </div> <div id="onesSelected"></div> <div id="threeSelected"></div> <div id="sixSelected"></div> <div id="twentyFourSelected"></div> </br> </br> </div> <div> <span class="placeholderText">Daily Energy Consumption</span> </br> <div id="dailyEnergyConsumptionVal">---</div> </br> </div> <div> <span class="placeholderText">Estimated Yearly Use</span> </br> <input type="radio" name="usageRadio" value="365" id="allYear" onclick="annualEnergyConsumption(365)" /> <label for="allYear">All year</label> <input type="radio" name="usageRadio" value="182" id="halfYear" onclick="annualEnergyConsumption(182)" /> <label for="halfYear">6 Months</label> <input type="radio" name="usageRadio" value="90" id="threeMonths" onclick="annualEnergyConsumption(90)" /> <label for="threeMonths">3 Months</label> <input type="radio" name="usageRadio" value="30" id="oneMonth" onclick="annualEnergyConsumption(30)" /> <label for="oneMonth">1 Month</label> <!-- <div id="daysUsed"><input type="number" id="hour" maxlength="2" min="1" onchange="annualEnergyConsumption(this.value)"></br> --> </div> </br> <div> <span class="placeholderText">Energy Consumption</span> </br> <div id="annualEnergyConsumption">---</div> </br> </div> <input type="submit" value="Save Product" onclick="displayStorage()" /> <input type="reset" onclick="resetForm()" id="resetButton" value="Reset" /> </div> <div id="right"> <div id="displayName">Selected Product:</div> <div id="displayAnnual">Annual Consumption:</div> </div> </form>
In the last statements of your function, there are two mistakes: if (missingFields = true) { // should be: missingFields == true alert("Please provide the following fields before continuing: \n" + strFields); } return false; return true; // You already returned false; did you mean to return false inside the if?