Excel/CSV connection with site - javascript

I am making an e-shop that has to be connected to an excel or CSV file.
More specifically I need to connect excel rows to input boxes (prices,bottles,etc). All those inputs will be connected to an input slider(type=range)just like the JS below.
I have researched this matter very much and someone told me I need to use XML. I can't use pure JS/Python because it needs to be updated constantly and I am completely clueless as to how I should proceed.
Let me know if anything is not clear.
Thanks in advance.
<script>
var city = document.getElementById('city')
var cityrepeat = document.getElementById('cityrepeat')
var state = document.getElementById('state')
var staterepeat = document.getElementById('staterepeat')
function setCity() {
cityrepeat.value = city.value
}
function setd() {
city.value = cityrepeat.value
}
function setState() {
staterepeat.value = state.value
}
</script>
City
<input id="city" type="text" onChange="setCity()" size=5/></br>
State
<input id="state" type="text" onChange="setState()" size=5/></br>
City repeat
<input id="cityrepeat" type="range" min="1" max="100" onChange="setd()"/>
<br>
State repeat
<input id="staterepeat" type="range"/>

You can send the form data to the backend and from there write it to an xls/csv file. Since you are using python, you can look for a package here

Related

Why is the input type "date" value not updating new values from the input

I am trying to get a date from the input type "date" but when I retrieve the data in JavaScript, only the default value that I set is retrieved all the time.
No matter what I do, I keep getting the default value instead of the new one I chose.
I couldn't find any solution from all the similar questions about this, please do not flag this question because I am already getting a warning that my last question was not well received by the community, I thought we are here to learn and asking stupid questions is part of it.
var getInput = document.querySelector("#year");
var data = getInput.value, dob = data.split("-"), byy = dob[0], bmm = dob[1], bdd = dob[2];
function process(){
console.log(byy)
}
<input id="year" type="date" value="2022-12-25" required><br>
<input id="goBtn" onclick="process()" type="button" value="Go">
Get the date value within the function you are calling.
function process() {
var getInput = document.querySelector("#year");
var data = getInput.value, dob = data.split("-"), byy = dob[0], bmm = dob[1], bdd = dob[2];
console.log(byy);
}
<input id="year" type="date" value="2022-12-25" required><br>
<input id="goBtn" onclick="process()" type="button" value="Go">
The variables were being assigned to immediately when the JavaScript executed, giving them the default value. They need to be assigned to at the time you press the go button.

Error 400 when submitting form but information is still received in google sheet

I am receiving a error 400 when submitting a form, yet the data is transferred to my Google Sheet as intended.
I've read up on what may cause a 400 error but my understanding is not advanced enough to spot the error in the code.
code.gs
function doGet() {
return HtmlService
.createTemplateFromFile('jSignature')
.evaluate();
}
function saveImage(bytes, sign){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponse');
var dateObj = Date.now();
var bytes = bytes.split(",")
var blob = Utilities.newBlob(Utilities.base64Decode(bytes[1]), 'image/png');
var fileName = blob.setName("Signature "+dateObj).getName();
var sigFolder = DriveApp.getFolderById("myFolder"); //replace with your folder id
var url = sigFolder.createFile(blob).getId();
Logger.log(url)
var carrier = sign.carrier;
var address = sign.address;
var dname = sign.dname;
var dnum = sign.dnum;
var date = sign.date;
var time = sign.time;
var tractortruck = sign.tractortruck;
var odom = sign.odom;
var imageCell = ss.getRange(ss.getLastRow()+1, 1, 1, 9).setValues([[carrier, address, dname, dnum, date, time, tractortruck, odom, url]]);
}
html
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=2, maximum-scale=1, user-scalable=0"/></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/willowsystems/jSignature/master/libs/jSignature.min.js"></script>
<style>
</style>
<body>
<center><h1><big><big>DRIVER VEHICLE INSPECTION REPORT</big></big></h1>
<h5>AS REQUIRED BY THE D.O.T. FEDERAL MOTOR CARRIER SAFETY REGULATIONS</h5></center><br>
<form id="customerForm" action="/action_page.php">
<div class="container">
<label for="carrier">Carrier:</label>
<select id="carrier" name="carrier" required>
<option value="My Company">My Company</option>
</select><br>
Location:
<table id= "Address">
<tr>
<td>PDX</td>
<td>EUG</td>
<td>SEA</td>
<td>SFO</td>
</tr>
<tr>
<td><input type="radio" id="PDX" oninput="this.className = '';EUG.className = '';SEA.className = '';SFO.className = ''" name="Address" value="PDX"></td>
<td><input type="radio" id="EUG" oninput="this.className = '';PDX.className = '';SEA.className = '';SFO.className = ''" name="Address" value="EUG"></td>
<td><input type="radio" id="SEA" oninput="this.className = '';EUG.className = '';PDX.className = '';SFO.className = ''" name="Address" value="SEA"></td>
<td><input type="radio" id="SFO" oninput="this.className = '';EUG.className = '';SEA.className = '';PDX.className = ''" name="Address" value="SFO"></td>
</tr>
</table>
<label for="Driver name">Driver Performing Inspection:</label>
<input type="text" id="dname" name="drivername" placeholder="Your full name" required><br>
<label for="Driver Employee ID number">Driver's Employee Number:</label><br>
<input type="number" id="dnum" name="drivernumber" placeholder="Your employee number" required><br><br>
<label for="Date">Date Performed:</label><br>
<input type="date" id="date" name="date" required><br><br>
<label for="Time">Time Performed:</label><br>
<input type="time" id="time" name="time" value="now" required><br><br>
<label for="Tractor/Truck#">Tractor / Truck #:</label><br>
<input type="number" id="tractor/truck" name="tractortrucknum" placeholder="Your vehicle number" required><br><br>
<label for="Odometer">Odometer Reading:</label><br>
<input type="number" id="odom" name="odometer" placeholder="Vehicle odometer reading" required><br><br>
<b><big>Signature:</big></b>
<div id="signature"></div><br>
<img id="rendered" src="" style="display:none">
<input type="submit" value="Submit and close" onclick="renderSignature();saveImage();"/>
</div>
</form>
</body>
<script>
$("#signature").jSignature({
'background-color': 'transparent',
'decor-color': 'transparent',
});
function renderSignature(){
$("img#rendered").attr("src",$('#signature').jSignature('getData','default'));
}
function saveImage(e){ //This sends the image src to saveImages function
var bytes = document.getElementById('rendered').src;
console.log(bytes);
var sign = {
carrier: document.getElementsByName('carrier')[0].value,
address: $('input[name="Address"]:checked').val(),
dname: document.getElementsByName('drivername')[0].value,
dnum: document.getElementsByName('drivernumber')[0].value,
date: document.getElementsByName('date')[0].value,
time: document.getElementsByName('time')[0].value,
tractortruck: document.getElementsByName('tractortrucknum')[0].value,
odom: document.getElementsByName('odometer')[0].value,
};
alert("saveImage successful");
google.script.run.saveImage(bytes, sign);
return
}
let date = new Date().toISOString().substr(0, 10);
document.querySelector("#date").value = date;
$(function(){
var d = new Date(),
h = d.getHours(),
m = d.getMinutes();
if(h < 10) h = '0' + h;
if(m < 10) m = '0' + m;
$('input[type="time"][value="now"]').each(function(){
$(this).attr({'value': h + ':' + m});
});
});
</script>
</html>
Ideally, I'd like to see the form take the user to a URL on submit. I think I can figure this out once we resolve the 400 issue. If anyone has advice, though, I'd love to hear it.
I cannot speak directly for Google sheets, but I suspect your code is okay.
Have a read of this: Google Sheets: Commonly Returned Errors
Namely this:
Error: Google returned with status code 400:
A Google Sheet Error 400 typically indicates that the credentials used in the integration are invalid. Try removing and re-adding the integration, updating the credentials if they have been changed at all for the Google Sheets account being used. If able to re-add without getting an error, that should resolve any invalid access errors and you can re-run the integration on your existing submissions. This error can also be a problem with "Protected sheets and ranges" if you've altered your spreadsheet lately.
If Google Sheets returns a Bad Request - "Unable to retrieve cells" error, this is because you do not have column labels in the first row of your sheet. You have to create the sheet and fields on your sheet across the top row first before they will show in Formstack - make sure the field names are the same as the field labels on your form.
I can only assume you submit the data and then immediately query it.
There's a very strong chance that the server has not processed / stored the data that you are currently trying to access.
This error can also be a problem with "Protected sheets and ranges" if you've altered your spreadsheet lately.
The solution would be non-sophisticated and would involve one of two things:
try / catch block to attempt to query the site / data & if an error is returned, just process the page without any data
Wait 1 second then try / catch query. If error - wait 2 seconds then try / catch query. Repeat with increasing durations until 5 seconds and then just load the page without any data if no data is able to be retrieved after 5 queries.
However it would be good to double check that these are correct with relation to your spreadsheet / code combination (we do not have access to your spreadsheet):
Your query is correctly formatted - particularly in reference to column names: 400 Bad Request : Invalid Query parameter value
The document you're trying to access is PUBLIC
The query has correct ranges references: Error: Unable to parse range
A correct API key is being used (if applicable): Google API Key for Google Sheets
Hopefully that helps, I've had similar issues with Sharepoint online queries before.
Most likely
Either the sheet 'FormResponse' does not exist in the spreadsheet to which the script is bound
DriveApp.getFolderById() does not contain a valid folder Id
Or you do not have the right to access this folder
This might seem dumb, but it doesn't seem as though I use /action_page.php to collect the data, it is all done in JS through the functions saveImage and renderSignature. When looking at an old version of my code, I realized it didn't use /action_page.php. So that must be something I picked up along the way from trying to improve my code, but it appears to be unnecessary. When removed, all of my info is saved and transfers over to the google sheet exactly as I need it to and I don't get a 400 error on submit.
Thank you all for your help! I hope this can help someone else.

Is there a way to nest an array inside of an object using the name attribute within a form?

I am building an full-stack application in where I have a form submitting data to one of my post routes. On this form, I have all of my input fields bundled into req.body.model, thanks to the fact that I can add a name attribute with square brackets around the key, like so name="model[height]".
This should equate to something like this:
model = {
height: //value,
weight: //value,
age: //value
}
However, I want one of the values to be an empty array so I can push URLS into the array, like so:
model = {
height: //value,
weight: //value,
age: //value,
urls: [//urls here]
}
Since you can automatically create an object using the name attribute, I was wondering if there was a way to create a nested array using the name attribute as well?
Code snippet
<form>
<input type="text" name="model[height]">
<input type="text" name="model[weight]">
<input type="text" name="model[age]">
// these 2 inputs would go into the urls key in the models object
<input type="text">
<input type="text">
<button>Submit</button>
</form>
Not sure if I worded this properly...but let me know if I can explain in further detail.
If you pass index next to the property you can create an array. Something like this
// these 2 inputs would go into the urls key in the models object
<input type="text" name="model[urls][0]">
<input type="text" name="model[urls][1]">
Not sure if I got what you are trying to do exactly, but it seems like you can first process the submitted data and then send the processed data to wherever you want to send it. It's a bit more verbose, but I feel like it may give you more flexibility when organising your data. So maybe you can do something like this:
html
<form name="model">
<input type="text" id="height">
<input type="text" id="weight">
<input type="text" id="age">
<input type="text" id="url1">
<input type="text" id="url2">
<button onclick="processForm()">Submit</button>
</form>
script
function processForm() {
let height = document.querySelector("#height").value;
let weight = document.querySelector("#weight").value;
let age = document.querySelector("#age").value;
let url1 = document.querySelector("#url1").value;
let url2 = document.querySelector("#url2").value;
let model = {
"height": height,
"weight": weight,
"age": age,
"url": [url1, url2]
}
// now you can send model object to where it is needed
}

Updated HTML from JavaScript variable

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

Populating a calculated value into another form

I have a small form that calculates a shipping cost, which is all working fine. I want the user to click Book Now and the fields are then populated.
All the fields have been populated correctly, its just the cost calculation doesn't populate on the form.
This is my code for calculting the cost
var values = [
[20,25,35,40],
[36,42,50,56],
[42,56,52,68],
[60,70,68,72],
];
function updateValue() {
var fromCountry = document.querySelector('input[name="from_country"]:checked').value;
var toCountry = document.querySelector('input[name="to_country"]:checked').value;
var totalValues = values[fromCountry-1][toCountry-1];
var quantity = document.querySelector('select[name="number"]');
var x = parseInt(quantity.value, 10);
if(fromCountry && toCountry) {
document.getElementById('cost').value = (totalValues * x);
}
}
This is the html
<input type="text" id="cost" name="cost" value="0" disabled="disabled" />
Then the other form looks like this:
<label for="cost">Estimated cost</label>
<input type="text" id="cost" name="cost" value="<?php echo $_POST['cost'];?>">
All the other fields populate fine but the cost one doesn't for some reason.
I believe if a text input is disabled its contents are not actually POSTed in the submission. Add a hidden input and populate it with the value and it should be sent in the request.
On the other hand, there is no reason why you cannot perform the same calculation on the server side using the values you do have. There is nothing stopping a savvy user from editing the "cost" on your page to give themself a nice discount.

Categories

Resources