I've been trying to build an application to submit form selections to an existing spreadsheet on a local machine. This is intended for a windows machine, but I am working on ubuntu, and don't have access to a windows development environment. With this, I'm trying to parse an excel document, find the bottom row, capture the 'ingredients' list, or other form values, then insert the value of the hash into the excel column and save the changes to the document. Any suggestions on where I should start would be great.
-- Thanks a million
//Script
$(document).ready(doInput);
function doInput(){
var ingreds = $('.ingredients');
var count = $('.count');
var runs = $('#runs');
var cb = $('.cb');
var bb = $('.bb');
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = twoDigitMonth + "/" + fullDate.getDate() + "/" + fullDate.getFullYear();
var bbDate = fullDate.getMonth() + 8;
cb.html("C&B:<br />" + currentDate);
if (bbDate > 12){
bb.html("BB:<br />" + "0" + (bbDate - 12) + "/" + fullDate.getDate() + "/" + (fullDate.getFullYear() + 1));
}else{
bb.html("Best By:<br />" + bbDate + "/" + fullDate.getDate() + "/" + fullDate.getFullYear());
}
var recipes = {
'Volvo': {
'Torq': 1231,
'Leather': 131,
'Blue': 22
},
'Jet': {
'HP': 1233,
'Leather': 121,
'Candy': 1313,
'Gas': 1313,
'Billiard': 223
},
'Mac': {
'Torq': 12111,
'Cheddar': 123
},
'Hog': {
'Torq': 475,
'Sugar': 12,
'Sheer': 11,
'Water': 2323,
'Wheels': 3
}
}
var recipe;
ingreds.html("Ingredients:<br />");
count.html("The Yield is:" + $('#yield').val() + "?<br />");
if ($("option:selected").val() == 'volv') {
recipe = recipes['Volvo'];
}else if($("option:selected").val() == 'jet') {
recipe = recipes['Jet'];
}else if($("option:selected").val() == 'mac') {
recipe = recipes['Mac'];
}else if($("option:selected").val() == 'hog') {
recipe = recipes['Hog'];
}
for (key in recipe){
if(key == 'Sugar'){
ingreds.append(key + ": " + recipe[key] * runs.val() + 'Lbs<br />');
}else{
ingreds.append(key + ": " + recipe[key] * runs.val() + 'g<br />');
}
}
return true;
}
body {
background: rgba(150,150,150,.5);
}
.container {
width: 80%;
margin: auto;
padding: 10px;
}
.ingredients {
padding: 10px;
padding-left: 20px;
}
.count {
margin-top: 25px;
font-weight: Bold;
color: #700;
}
.submit,
.ingredients,
.flavor,
.runs,
.yieldShell,
.bestBy,
.cb,
.bb {
min-width: 215px;
}
.count {
min-width: 190px;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
.row:before,
.row:after {
display: table;
content: " ";
}
.row:after {
clear: both;
}
.col-sm-4{
position: relative;
min-height: 1px;
padding-right: 15px;
padding-left: 15px;
}
#media (min-width: 540px) {
.container {
width: 750px;
}
.col-sm-4 {
float: left;
width: 33.33333333333333%;
}
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="container">
<form oninput="doInput()">
<div class="row">
<div class="flavor col-sm-4">
Flavor:<br />
<select name="flavors">
<option value="volv" selected="selected">Volvo</option>
<option value="jet">Jet</option>
<option value="mac">Mac</option>
<option value="hog">Hog</option>
</select>
</div>
<div class="runs col-sm-4">
Number of runs:<br />
<input type="number" id="runs" name="runs" value="1">
</div>
</div>
<div class="row">
<div class="ingredients col-sm-4"></div>
<div class="yieldShell col-sm-4">
<div class="yield">Yield:<br />
<input type="number" id="yield" name="yield" value="450">
</div>
<div class="count col-sm-4"></div>
</div>
</div>
<div class="row">
<div class="submit col-sm-4">
<input type="submit" value="Save to Production Log?">
</div>
<div class="bestBy col-sm-4">
<div class="row">
<div class="col-sm-4 cb"></div>
</div>
<div class="row">
<div class="col-sm-4 bb"></div>
</div>
</div>
</div>
</form>
</div>
Are you not looking at this from the wrong angle?
Rarely would you try to access an Excel document directly, since the quantity of 'irrelevant' data is huge (data needed by Excel to reconstruct the page itself, but not directly related to the data the user is storing - meta-data if you will; i.e. font used, size of font, etc.).
Usually you would output the data to a CSV and allow the user to import the data into any spreadsheet program, which gives you greater flexibility and is simpler to code.
In terms of adding the data, you could easily open the existing CSV and append new data, or search the file and insert the data where required. However, if others are to use the CSV then I'd save the data in a single-table database as well as in the CSV. Then you simply construct a new CSV each time, overwriting any existing file if necessary.
No code help here at present, and I might be wrong, but this is the approach I have used and seen used.
Related
I am learning JS and jQuery. As an exercise, I am trying to create a basic contact list. I need to be able to add and delete contacts from the list.
But I am having some bugs in my result. I can't find the cause of it. If anyone can advise? I would be most gratefull.
BUG 1:
When running the snippet below, you will see some sample contacts generated in the list. You can delete a contact just fine. You can also add a contact. But after adding a contact, the delete buttons stop working.
First I thought the issue was probably a missing character in my .html() method on the contacts objects. But I see no errors there. Anyone?
BUG 2:
Inside the $renderContacts function. You can see the const html. This should replace the let html and for loop below. And it works for long list of contacts. But the first contact is rendered as [object Object]. I don't see the cause. Might these 2 bugs be related?
Please advise.
Many thanks! :)
$(document).ready(function() {
// Array to store all contacts
let contactsArr = [];
// counter to create incrementing ID
let contactID = 0;
// Constructor for contact objects
function Contact(firstName, lastName, email, phone, address) {
this._id = contactID += 1;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
this.address = address;
contactsArr.push(this);
};
// Some getters, setters and a methods for contact objects
Contact.prototype = {
constructor: Contact,
set(id) {
console.log(`ID is generated on input and may not be changed`)
},
get id() {
return this._id;
},
set firstName(firstName) {
this._firstName = firstName;
},
get firstName() {
return this._firstName;
},
set lastName(lastName) {
this._lastName = lastName;
},
get lastName() {
return this._lastName;
},
set email(emailaddress) {
this._email = emailaddress;
},
get email() {
return this._email;
},
set phone(phone) {
this._phone = phone;
},
get phone() {
return this._phone
},
set address(address) {
this._address = address;
},
get address() {
return this._address
},
toHTML() {
const renderCell = (content, cssClass = "") => `<div class="table-cell ${cssClass}">${content}</div>`;
const deleteContact = `<span title="Delete contact" class="delete-contact far fa-trash-alt fa-sm"></span>`;
const rowActions = renderCell(deleteContact, "text-right contact-actions");
return '<div class="table-row">' +
renderCell(this.id, "contact-id text-right") +
renderCell(this.firstName, "first-name") +
renderCell(this.lastName, "last-name") +
renderCell(this.email, "email") +
renderCell(this.phone, "phone") +
renderCell(this.address, "address") +
rowActions + '</div>';
},
};
// SAMPLE CONTACTS
new Contact("John", "Cubico", "mymail#mail.com", "111-555-6666", "Belgium");
new Contact("Lisa", "The Sailor", "mymail#mail.com", "111-666-7777", "Spain");
new Contact("Christophe", "From next door", "mymail#mail.com", "111-777-8888", "Germany");
new Contact("Aïsha", "From elsewere", "mymail#mail.com", "111-888-9999", "Brussels, Holland");
// Render Samples
function $renderContacts(arr = contactsArr) {
//const html = arr.reduce((all, one) => all += one.toHTML()); // ==>> 1st not rendering
let html = ``;
for (let i = 0; i < arr.length; i++) {
html += arr[i].toHTML();
};
$("#contacts-list").append(html);
};
$renderContacts();
// BUTTONS & ACTIONS
// Add contact
$("#add-contact").on("click", () => {
const $firstName = $("#first-name").val();
const $lastName = $("#last-name").val();
const $email = $("#email").val();
const $phone = $("#phone").val();
const $address = $("#address").val();
const contact = new Contact($firstName, $lastName, $email, $phone, $address); // create contact
$("#contacts-list").append(contactsArr[contactsArr.length - 1].toHTML()); // add contact to DOM
});
// Delete contact
$(".delete-contact").on("click", (event) => {
const arr = contactsArr.slice();
const $id = Number($(event.currentTarget).closest(".table-row").find(".contact-id").text());
const i = arr.findIndex(contact => contact.id == $id);
contactsArr = arr.slice(0, i).concat(arr.slice(i + 1)); // delete from array of contacts
$(event.currentTarget).closest(".table-row").remove(); // delete only this contact from DOM
});
});
html {}
.active {}
.inactive {
color: #b8b8b8;
}
.table td,
.table th {
padding: 0.5rem;
}
.text-large {
font-size: 1.5rem;
}
.relative {
position: relative;
}
/*** Search ***/
#search-input {
font-size: 2rem;
font-weight: 300;
}
span#search-btn {
position: absolute;
right: 0;
top: 0;
width: 50px;
height: 47px;
padding: 10px;
box-sizing: border-box;
font-size: 1.6rem;
line-height: 34px;
}
/*** Contacts table ***/
.table-header {
padding: 15px 0 5px;
}
.table-row {
display: grid;
grid-template-columns: 30px repeat(5, 1fr) 100px;
grid-column-gap: 20px;
margin: 3px 0;
padding: 2px 0;
background: #f0f0f0;
}
.table-cell {
padding: 3px;
}
.editable-cell {
background: rgba(255, 255, 255, 0.6);
}
.contact-actions span {
line-height: 18px;
padding: 3px;
display: inline-block;
width: 26px;
text-align: center;
}
/*** Form ***/
#form-new-contact {
align-items: end;
margin: 0 -15px;
padding: 15px;
}
#add-contact {
width: 100%;
}
<html>
<head>
<title>jQuery contacts app</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<header>
<div class="container text-center mt-4 mb-4">
<h1>jQuery contacts app</h1>
</div>
</header>
<main>
<div class="container">
<form id="form-new-contact" action="" method="POST" class="table-row mt-4 mb-4">
<div class="text-center"><span class="fas fa-user-plus fa-sm mb-2"></span></div>
<div class="">
<label for="first-name">First name:</label>
<input name="first-name" id="first-name" class="form-control form-control-sm" type="text" value="Voornaam" placeholder="John" required>
</div>
<div class="">
<label for="last-name">Last name:</label>
<input name="last-name" id="last-name" class="form-control form-control-sm" type="text" value="Achternaam" placeholder="Doe" required>
</div>
<div class="">
<label for="email">Email:</label>
<input name="email" id="email" class="form-control form-control-sm" type="email" value="E-mailadres" placeholder="john#doe.com" required>
</div>
<div class="">
<label for="phone">Phone:</label>
<input name="phone" id="phone" class="form-control form-control-sm" type="tel" value="Telefoon/GSM" placeholder="555-666-8989" required>
</div>
<div class="">
<label for="address">Address:</label>
<input name="address" id="address" class="form-control form-control-sm" type="text" value="Adres" placeholder="Somewhere" required>
</div>
<div class="">
<button id="add-contact" type="button" class="btn btn-sm btn-success"><i class="fas fa-plus-circle mr-2"></i>Add</button>
</div>
</form>
<div class="table">
<div class="table-row table-header">
<div id="id-header" class="text-right">
<h3 class="h6">ID</h3>
</div>
<div id="first-name-header" class="">
<h3 class="h6">Firstname</h3>
</div>
<div id="last-name-header" class="">
<h3 class="h6">Lastname</h3>
</div>
<div id="email-header" class="">
<h3 class="h6">Email</h3>
</div>
<div id="phone-header" class="">
<h3 class="h6">Phone</h3>
</div>
<div id="address-header" class="">
<h3 class="h6">Address</h3>
</div>
<div class="text-right">
<h3 class="h6">Actions</h3>
</div>
</div>
<div id="contacts-list" class="">
</div>
</div>
</div>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
BUG1:
You can't fire on click function on dynamically generated DOM element like that.
Add event listener to your element (using pure JS):
elem.addEventListener("click", func, false);
Or change syntax of your click function to this (using jQuery):
$(document).on("click",'.delete-contact', (event) => {
// your code here
});
BUG2:
I don't know why this function acts like that, but you always have to pass default string parameter. Look to the next lines I made:
let html = arr.reduce((all, one) => all += one.toHTML(), '');
Working fiddle
I have the following page, which is a wikisearch page that queries multiple wikipidia pages for the search term. The page has the title and input box somewhere around the middle; however, when I click on the botton, the title slides up, and so the input box. But the input box slides all way up covering the title. I think!... how can I prevent the inputbox from covering the title? or make the title stays at the top of page? Thanks
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
console.log(searchStr);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
console.log(response.query);
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary" onclick="#">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Insted of using $('#title').slideUp(3000) try use $('#title').animate({'margin-top': '0'}, 3000);
Then the title will remain.
Also, you might want to remove onclick="#" from <button id="search" class="btn btn-primary" onclick="#">Search</button>
Example below.
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$('#title').animate({'margin-top': '0'}, 3000);
//$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Add this to the h1 class
h1 {
z-index: 1000;
}
Now let's say you needed something to then go on top of the header, you'd give that element's class a z-index of something higher than 1,000, so maybe 1,001! If you needed something to go behind, simply make it 999 or lower. Using 1,000 gives you a lot of free range in either direction (+/-) to work with.
I'm trying to render >3 graphs, using Dygraphs in JS.
Using some example codes, I was able to create a dummy for my work, just like this.
The demo works as it should, but here is my scenario:
I am trying to render 3 or more graphs with values from different ranges. I want to zoom in a time peroid on a graph and I want all the other graphs to zoom with it.
Right now, said graph will be zoomed and the others are going to be messed up:
$(document).ready(function() {
var someData = [
"2009/01/01,10,11,12\n" +
"2009/01/02,12,10,11\n" +
"2009/01/03,9,10,13\n" +
"2009/01/04,5,20,15\n" +
"2009/01/05,8,3,12\n",
"2009/01/01,510,511,512\n" +
"2009/01/02,518,510,511\n" +
"2009/01/03,519,510,513\n" +
"2009/01/04,525,520,515\n" +
"2009/01/05,508,513,512\n",
"2009/01/01,0.10,0.11,0.01\n" +
"2009/01/02,0.12,1,0.11\n" +
"2009/01/03,0.09,0.10,0.13\n" +
"2009/01/04,0.05,0.20,0.15\n" +
"2009/01/05,0.08,0.03,0.12\n",
"2009/01/01,110,111,112\n" +
"2009/01/02,112,110,111\n" +
"2009/01/03,109,110,113\n" +
"2009/01/04,105,120,115\n" +
"2009/01/05,108,103,112\n"
];
var graphs = ["x", "foo", "bar", "baz"];
var titles = ['', '', '', ''];
var gs = [];
var blockRedraw = false;
for (var i = 1; i <= 4; i++) {
gs.push(
new Dygraph(
document.getElementById("div" + i),
someData[i - 1], {
labels: graphs,
title: titles[i - 1],
legend: 'always'
}
)
);
}
var sync = Dygraph.synchronize(gs);
function update() {
var zoom = document.getElementById('chk-zoom').checked;
var selection = document.getElementById('chk-selection').checked;
sync.detach();
sync = Dygraph.synchronize(gs, {
zoom: zoom,
selection: selection
});
}
$('#chk-zoom, #chk-selection').change(update);
});
.chart {
width: 500px;
height: 300px;
}
.chart-container {
overflow: hidden;
}
#div1 {
float: left;
}
#div2 {
float: left;
}
#div3 {
float: left;
clear: left;
}
#div4 {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph.js"></script>
<script src="http://dygraphs.com/src/extras/synchronizer.js"></script>
<p>Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.</p>
<p>To use this, source <code>extras/synchronizer.js</code> on your page. See the comments in that file for usage.</p>
<div class="chart-container">
<div id="div1" class="chart"></div>
<div id="div2" class="chart"></div>
<div id="div3" class="chart"></div>
<div id="div4" class="chart"></div>
</div>
<p>
Synchronize what?
<input id="chk-zoom" checked="" type="checkbox">
<label for="chk-zoom">Zoom</label>
<input id="chk-selection" checked="" type="checkbox">
<label for="chk-selection">Selection</label>
</p>
For me it looks like that, the other graphs want to show the same value range for the selected time peroid. If this is the case, then do I just need to redraw the other graphs somehow?
Below, I have modified your code (only 2 lines) and now I think it is working as you need.
Inside the synchronize options, I have added the option "range" set to false. With this option, the y-axis is not synchronized, which is what you need.
The other thing I´ve done, is to force a call to update() after the graphs synchronization. In the way you had the code, the update was not called until a checkbox was modified, so at the first, the graphs synchronization was not working.
I hope this could help you and sorry for not answering before ;)
$(document).ready(function() {
var someData = [
"2009/01/01,10,11,12\n" +
"2009/01/02,12,10,11\n" +
"2009/01/03,9,10,13\n" +
"2009/01/04,5,20,15\n" +
"2009/01/05,8,3,12\n",
"2009/01/01,510,511,512\n" +
"2009/01/02,518,510,511\n" +
"2009/01/03,519,510,513\n" +
"2009/01/04,525,520,515\n" +
"2009/01/05,508,513,512\n",
"2009/01/01,0.10,0.11,0.01\n" +
"2009/01/02,0.12,1,0.11\n" +
"2009/01/03,0.09,0.10,0.13\n" +
"2009/01/04,0.05,0.20,0.15\n" +
"2009/01/05,0.08,0.03,0.12\n",
"2009/01/01,110,111,112\n" +
"2009/01/02,112,110,111\n" +
"2009/01/03,109,110,113\n" +
"2009/01/04,105,120,115\n" +
"2009/01/05,108,103,112\n"
];
var graphs = ["x", "foo", "bar", "baz"];
var titles = ['', '', '', ''];
var gs = [];
var blockRedraw = false;
for (var i = 1; i <= 4; i++) {
gs.push(
new Dygraph(
document.getElementById("div" + i),
someData[i - 1], {
labels: graphs,
title: titles[i - 1],
legend: 'always'
}
)
);
}
var sync = Dygraph.synchronize(gs);
update();
function update() {
var zoom = document.getElementById('chk-zoom').checked;
var selection = document.getElementById('chk-selection').checked;
sync.detach();
sync = Dygraph.synchronize(gs, {
zoom: zoom,
range: false,
selection: selection
});
}
$('#chk-zoom, #chk-selection').change(update);
});
.chart {
width: 500px;
height: 300px;
}
.chart-container {
overflow: hidden;
}
#div1 {
float: left;
}
#div2 {
float: left;
}
#div3 {
float: left;
clear: left;
}
#div4 {
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://dygraphs.com/dygraph.js"></script>
<script src="http://dygraphs.com/src/extras/synchronizer.js"></script>
<p>Zooming and panning on any of the charts will zoom and pan all the others. Selecting points on one will select points on the others.</p>
<p>To use this, source <code>extras/synchronizer.js</code> on your page. See the comments in that file for usage.</p>
<div class="chart-container">
<div id="div1" class="chart"></div>
<div id="div2" class="chart"></div>
<div id="div3" class="chart"></div>
<div id="div4" class="chart"></div>
</div>
<p>
Synchronize what?
<input id="chk-zoom" checked="" type="checkbox">
<label for="chk-zoom">Zoom</label>
<input id="chk-selection" checked="" type="checkbox">
<label for="chk-selection">Selection</label>
</p>
I want to capture 2 values (product name and energy consumption)from a form and store it using local Storage.
OnClick I want to display the stored values on the side of the form.
What is working
local storage is getting set.
Issues (in the commented function compareSetup)
1) My guess is I am not getting the selected product nor the energy values from the form itself.
2) wrote the display logic but getting error on that line
Uncaught SyntaxError: Unexpected identifier.
I tried 2 different ways. I am newbie hence trying different syntax
3) Resources tab in Chrome shows
callAnnual as undefined
callProduct as 0
4) alerts inside function did not work
I missing something. either logically or syntaxwise or both.
Can some one guide me please. Thanks for your time.
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 configureDropDownLists(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');
//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}
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;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function configureProductDropDownLists(product) {
document.getElementById('wattage').innerText = wattage[product.value];
}
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";
}
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";
}
}
/*
function compareSetup(){
// I am trying to set the local storage for 2 things : selected [product name and Annual Energy Consumption]. End goal is to use them inorder to plot a chart
//initialize the selected product and annual consumption by calling their latest values on submit
var submittedProduct = document.getElementById("products").options.selectedIndex;
var submittedAnnualEnergyConsumption = document.getElementById("annualEnergyConsumption").value;
//alert(submittedProduct);
//setting the local storage with a key and variable name which was defined above
localStorage.setItem("callProduct", submittedProduct);
localStorage.setItem("callAnnual", submittedAnnualEnergyConsumption);
//get Item with a key and display
var displayName = localStorage.getItem("callProduct");
//alert(callProduct);
displayName = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual").innerHTML = localStorage.getItem parseInt(("callAnnual"));
// return false as I dont want the form to submit
return false;
}
*/
$(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();
});
});
/*
annualCost = function() {
// utility rate currently is hard coded but this will come from the database and shall be inputted by user once. Utility Rate does not change that often
var utilityRate = 0.11;
var button = document.getElementById('annualCost');
var annualCost = parseFloat( annualEnergy * utilityRate).toFixed(2);
document.getElementById('annualCostOperation').innerText= "$" + annualCost ;
}
*/
#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;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form method="post" onSubmit="return compareSetup()">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="ddl" onchange="configureDropDownLists(this,document.getElementById('products'))">
<option value="">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="configureProductDropDownLists(this)">
<option selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">---</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="AllYear" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="halfYear" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="threeMonths" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="oneMonth" 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" />
</div>
<div id="right">
<div id="displayName">Selected Product 1</div>
<div id="displayAnnual">Selected Product1's Annual Consumption</div>
</div>
<!--
<div id="right">
</form>
<div>
<span class="placeholderText">Enter your Utility Rate per Kw/h</span></br>
<span><input type="number" id="utilityRate" /></span>
</br></br>
</div>
<div>
<span class="placeholderText"><button id="annualCost" onclick='annualCost()'>Annual Cost to Operate</button></span></br>
<span id="annualCostOperation" /></span>
</div>
</div>
-->
</form>
Your scope access of '$' as undefined should be a dead give away as to why the remainder of the code is not working. Once you have called the '$' bit of code within the proper scope it will work.
hi i am acquiring the image from the scanner device successfully i want to store that image in data base i am thinking that i need to convert into byte array then pass to controller but i am not able to convert that image into byte array.
can any one please suggest me that is it right approach or not,if it is wrong then what is the alternate way please help me.
this is my code.
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<title>Scanning documets</title>
<script type="text/javascript"
src="http://direct.asprise.com/scan/javascript/base/scanner.js"></script>
<!-- required for scanning -->
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- optional -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css"
rel="stylesheet">
<!-- optional -->
<style type="text/css">
img.zoom {
margin-right: 4px;
}
body {
margin: 20px 10px;
}
</style>
<script>
// -------------- Optional status display, depending on JQuery --------------
function displayStatus(loading, mesg, clear) {
$('#info').empty(); // jQuery is used
if (loading) {
$('#info')
.html(
(clear ? '' : $('#info').html())
+ '<p><img src="http://asprise.com/legacy/product/_jia/applet/loading.gif" style="vertical-align: middle;" hspace="8"> '
+ mesg + '</p>');
} else {
$('#info').html((clear ? '' : $('#info').html()) + mesg);
}
}
// -------------- scanning related code: independent of any 3rd JavaScript library --------------
/* function scanSimple() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SIMPLE_SCAN, // simple scan without the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
null);
}
*/
function scan() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN, // normal scan with the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS, {
'wia-version' : 2
});
}
/* function scanThenUpload() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN_THEN_UPLOAD, // scan and then upload directly in the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
{
'upload-url': 'http://asprise.com/scan/applet/upload.php?action=upload' // target URL
,'format': 'PDF'
});
} */
/** Use this callback function to get notified about the scan result. */
function myCallBackFunc(success, mesg, thumbs, images) {
var logText;
displayStatus(false, '', true);
logText = 'Callback function invoked: success = ' + success
+ ", mesg = " + mesg;
logText += '\nThumbs: ' + (thumbs instanceof Array ? thumbs.length : 0)
+ ", images: " + (images instanceof Array ? images.length : 0)
+ ",image name" + (images instanceof Array ? images.name : 0);
logToConsole(logText, !(success || mesg == 'User cancelled.'));
displayStatus(false, '<pre>' + logText + '</pre>', true);
for (var i = 0; (images instanceof Array) && i < images.length; i++) {
addImage(images[i], document.getElementById('images'));
}
}
/** We use this to track all the images scanned so far. */
var imagesScanned = [];
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
var elementImg = createDomElementFromModel({
'name' : 'img',
'attributes' : {
'src' : imgSrc,
'height' : '100',
'class' : 'zoom'
}
});
$('<input>').attr({
type : 'hidden',
name : '',
})
$('#imageData').val(imgSrc);
domParent.appendChild(elementImg);
// optional UI effect that allows the user to click the image to zoom.
enableZoom();
}
function submitForm1() {
displayStatus(true, "Submitting in progress, please standby ...", true);
com_asprise_scan_submit_form_with_images('form1', imagesScanned,
function(xhr) {
alert("image :" + imagesScanned);
if (xhr.readyState == 4) { // 4: request finished and response is ready
displayStatus(false,
"<h2>Response from the server: </h2>"
+ xhr.responseText, true);
alert("before");
document.getElementById("form1").submit();
}
});
}
</script>
</head>
<body style="margin: 10px 30px;">
<div
style="display: block; position: absolute; right: 30px; top: 20px;">
<!-- <a href="http://asprise.com/" target=_blank> <img src="http://asprise.com/res/img/nav/logo.fw.png"/> </a> -->
</div>
<h2></h2>
<!-- <p style="color: #9eadc0;">For evaluation purpose only. Please order a license from <a href="http://asprise.com/" target=_blank>asprise.com</a>
| View source code of this page
</p> -->
<div class="panel panel-info" style="margin: 20px 0px;">
<div class="panel-heading">
<h3 class="panel-title">Scann your docs:</h3>
</div>
<div class="panel-body">
<form id="form1" action="<c:url value='/upload'/>" method="POST"
enctype="multipart/form-data" target="_blank">
<!-- <label for="field1"
style="display: inline-block; width: 150px; text-align: right;">Field
1</label> <input id="field1" name="field1" type="text" value="value 1" /> <input
type="file" name="file" /> <br> -->
<span style="height: 4px;"></span><br> <label
style="display: inline-block; width: 150px; text-align: right;">Documents</label>
<button type="button" class="btn btn-info" onclick="scan();">Scan</button>
<!-- <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button>
<button type="button" class="btn btn-default" onclick="scanThenUpload();">Scan Then Upload</button> -->
<div id="images" style="margin-left: 154px; margin-top: 10px;">
<input type="hidden" name="imageName" value="" />
</div>
<input type="button" class="btn btn-primary" value="Submit form"
onclick="submitForm1();"
style="margin-left: 154px; margin-top: 20px;">
</form>
</div>
</div>
<div id="info" class="well"
style="display: block; background-color: #fff; height: 500px; margin-top: 12px; padding: 12px; overflow: scroll;">
<p>
<i>Information window</i>
</p>
</div>
<script src="http://yyx990803.github.io/zoomerang/zoomerang.js"></script>
<script>
function enableZoom() {
Zoomerang.config({
maxWidth : window.innerWidth, // 400,
maxHeight : window.innerHeight, // 400,
bgColor : '#000',
bgOpacity : .85
}).listen('.zoom');
}
</script>
</body>
</html>
You can get the image binary in BASE64 format. The imgObj.data in below code is the BASE64 format of image object:
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
...
To get the actual binary bytes, you can use:
var bin = window.atob(imgObj.data)
For a complete discussion of converting BASE64 to binary, please refer to: Base64 encoding and decoding in client-side Javascript
For a complete usage of scanner.js, you may consult Developer guide to scanner.js: cross-Browser HTML/JavaScript Scanning - Acquires images from scanners to web pages (Java, C# ASP.NET, PHP)