Thanks for the previous answer.
I have added a some more drawings to the canvas.I have also times(*) everything by 3 so I can see the lines better.
There is a straight line from the top to the bottom.
Is there a way to figure out where "var hdr" would hit that line?
h1 needs to be calculated for when hdr+h2 hits the line.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var p1=7.5*3;
var p2=10.25*3;
var lp=16
var max = lp; // how many times
ctx.moveTo(0,0);
for(i=1; i <= max; i++){
ctx.lineTo(p2*(i-1),p1 * i);
ctx.lineTo(p2 * i,p1 * i);
}
ctx.lineTo(p2*lp,p1*lp);
ctx.lineTo(0,0);
ctx.stroke();
var htx = c.getContext("2d");
var h1=100*3//h1 needs to be calculated
var h2=12*3
var h3=3*3
var hdr=80*3
htx.rect(h1,0,h3,h2);
htx.stroke();
ctx.lineTo(h1,h2);
ctx.lineTo(h1,hdr);
ctx.stroke();
</script>
</body>
</html>
This code has progressed quite well, how do I scale this so it always fits in the canvas?
<!DOCTYPE html>
<html>
<body>
<label for="text1">LP:
<input type="text" size="5" maxlength="5" name="text1" value="16" id="lp" />
</label>
<label for="text2">p1:
<input type="text" size="5" maxlength="5" name="text2" value="7.50" id="p1" />
</label>
<label for="text3">p2:
<input type="text" size="5" maxlength="5" name="text2" value="10.0" id="p2" />
</label>
<label for="text4">h2:
<input type="text" size="5" maxlength="5" name="text4" value="12" id="h2" />
</label>
<label for="text5">hdr:
<input type="text" size="5" maxlength="5" name="text5" value="80" id="hdr" />
</label>
<input type="button" value="Calculate" onclick="calc()">
<br>
<br>
<br>
<br>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;">
<br />Your browser does not support the HTML5 canvas tag.</canvas>
<script type="text/javascript">
function calc() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var p1 = parseFloat(document.getElementById("p1").value);
var p2 = parseInt(document.getElementById("p2").value);
var lp = parseInt(document.getElementById("lp").value);
var max = lp; // how many times
ctx.moveTo(0, 0);
for (i = 1; i <= max; i++) {
ctx.lineTo(p2 * (i - 1), p1 * i);
ctx.lineTo(p2 * i, p1 * i);
}
ctx.lineTo(p2 * lp, p1 * lp);
ctx.lineTo(0, 0);
ctx.stroke();
var htx = c.getContext("2d");
var h2 = parseInt(document.getElementById("h2").value);
var h3 = 3
var hdr = parseInt(document.getElementById("hdr").value);
var h1 = ((h2 + hdr) / p1 * p2) //h1 needs to be calculated
htx.rect(h1, 0, h3, h2);
htx.stroke();
ctx.lineTo(h1, h2);
ctx.lineTo(h1, hdr + h2);
ctx.stroke();
alert(h1)
}
</script>
</body>
</html>
thanks
Related
I have a Google Apps Script web app which has a form attached, for example:
<form id="form">
<input type="range" min="0" max="3" name="mb1" value="0">
<input type="range" min="0" max="3" name="mb2" value="0">
<input type="range" min="0" max="3" name="mb3" value="0">
etc...
<input id="submit" type="submit" style="display: none" onclick="this.value='Submitting ...'; google.script.run.withSuccessHandler(formSubmitted) .writeForm(this.parentNode); return false;">
</form>
The Code.gs file has a writeForm(form) function, which can access the form input values like so:
var mb1 = form.mb1;
var mb2 = form.mb2;
etc...
However, this approach is inefficient with many such inputs (I have around 80). Much better would just be to get the values when they're being processed in a loop, like so:
for(var i = 0; i <= 80; i++) {
var formItemID = "mb"+i;
console.log(form.formItemID);
}
However, this of course does not work, as it looks for form inputs with the id "formItemID". I've taken a look at some functionality of the HTMLFormElements class which should be being sent, but Apps Script doesn't seem to implement this fully, and I can't find documentation of the form.ItemName property. Is there a way to achieve this functionality without calling for each form input separately?
You could always just loop through the form elements and get the input values. This will send an array to the server.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="form" name="form">
<input class="range" type="range" min="0" max="3" value="0">
<input class="range" type="range" min="0" max="3" value="0">
<input class="range" type="range" min="0" max="3" value="0">
<br>
<input id="button" type="button" onclick="onClick()">
</form>
<script>
function onClick() {
var form = document.getElementById("form");
var vals = [];
for( var i=0; i<form.elements.length; i++ ) {
if( form.elements[i].className === "range" ) {
vals.push(form.elements[i].value);
}
}
google.script.run.getForm(vals);
}
</script>
</body>
</html>
Server side, Your form is sent as a object with key as input name and value as input values. Your form will look like:
{
mb1:0,
mb2:1,
mb3:0
}
To access the values, You can use form.mb1 as you've used or form['mb1']. To use variables as keys, always use the bracket [] notation
for(var i = 0; i <= 80; i++) {
var formItemID = "mb"+i;
console.log(form[formItemID]);//Note bracket notation
}
Or without a for loop,
var valuesArr = Object.keys(form).map(function(key){return form[key];})
Form:
<form action="/test" method="GET">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
How to change URL form with GET method?
Before: test?cat3=1&cat3=5&cat3=8&cat3=18
After: test?cat3=1,5,8,18
I want to use jQuery.
Many thanks!
Here you go! This example, using jQuery, will grab your form elements as your question is asking and perform a GET request to the desired URL. You may notice the commas encoded as "%2C" - but those will be automatically decoded for you when you read the data on the server side.
$(document).ready(function(){
$('#myForm').submit(function() {
// Create our form object. You could optionally serialize our whole form here if there are additional parameters in the form you want
var params = {
"cat3":""
};
// Loop through the checked items named cat3 and add to our param string
$(this).children('input[name=cat3]:checked').each(function(i,obj){
if( i > 0 ) params.cat3 += ',';
params.cat3 += $(obj).val();
});
// "submit" our form by going to the properly formed GET url
var url = $(this).attr('action') + '?' + $.param( params );
// Sample alert you can remove
alert( "This form will now GET the URL: " + url );
// Perform the submission
window.location.href = url;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" id="myForm">
<input name="cat3" value="1" type="checkbox">
<input name="cat3" value="5" type="checkbox">
<input name="cat3" value="8" type="checkbox">
<input name="cat3" value="18" type="checkbox">
<input type="submit" value="SUBMIT">
</form>
My friend found a solution:
$(document).ready(function() {
// Change Url Form: &cat3=0&cat3=1&cat3=2 -> &cat3=0,1,2
var changeUrlForm = function(catName){
$('form').on('submit', function(){
var myForm = $(this);
var checkbox = myForm.find("input[type=checkbox][name="+ catName +"]");
var catValue = '';
checkbox.each(function(index, element) {
var name = element.name;
var value = element.value;
if (element.checked) {
if (catValue === '') {
catValue += value;
} else {
catValue += '‚' + value;
}
element.disabled = true;
}
});
if (catValue !== '') {
myForm.append('<input type="hidden" name="' + catName + '" value="' + catValue + '" />');
}
});
};
// Press 'Enter' key
$('.search-form .inputbox-search').keypress(function(e) {
if (e.which == 13) {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
}
});
// Click to submit button
$('.search-form .btn-submit').on('click', function() {
changeUrlForm('cat3');
changeUrlForm('cat4');
alert(window.location.href);
$(".search-form").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/test" method="GET" class="search-form">
<input name="cat3" value="1" type="checkbox">1
<input name="cat3" value="3" type="checkbox">3
<input name="cat3" value="5" type="checkbox">5
<input name="cat3" value="7" type="checkbox">7
<br />
<input name="cat4" value="2" type="checkbox">2
<input name="cat4" value="4" type="checkbox">4
<input name="cat4" value="6" type="checkbox">6
<br />
<br />
Submit
<br />
<br />
<input type="text" placeholder="Search" class="inputbox-search" />
</form>
I replicated the Developer's example code with success. When i insert a div into the form it fails. How can i submit 'form div input' to a server side function?
* i believe divs and spans are allowed inside forms from here.
* uncommenting the divs causes the div 'output' not to update.
html:
<form id="myForm">
<!--><div>-->
<input name="myEmail" type="text" />
<input type="submit" value="Submit"
onclick="google.script.run.withSuccessHandler(updateEmail)
.processForm(this.parentNode)" />
<!--></div>-->
</form>
<div id="output">
</div>
<script>
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
code.gs
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Web App').setSandboxMode(HtmlService
.SandboxMode.NATIVE);
return html;
}
function processForm(formObject) {
var response = "";
response = formObject.myEmail;
return response;
};
Edit:
changed:
<input type="button" value="Submit"
to:
<input type="submit" value="Submit"
I changed the HTML file to this:
<form id="myForm">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"
onclick="processFormJs(this.parentNode)" />
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
And added a console.log('argDivParent: ' + argDivParent); statement. Then in developer tools, show the console. I get this error:
argDivParent: [domado object HTMLDivElement DIV]
Failed due to illegal value in property: 0
this.ParentNode is referring to the DIV and not the FORM. If I take out the DIV, the object returned is:
argDivParent: [domado object HTMLFormElement FORM]
Not:
argDivParent: [domado object HTMLDivElement DIV]
A DIV probably doesn't automatically put INPUT values into it's parent object.
This code does work with a DIV:
<form id="myForm" onsubmit="processFormJs(this)">
<div>
<input name="myEmail" type="text" />
<input type="button" value="Submit"/>
</div>
</form>
<div id="output"></div>
<script>
window.processFormJs = function(argDivParent) {
console.log('argDivParent: ' + argDivParent);
google.script.run.withSuccessHandler(updateEmail)
.processForm(argDivParent)
};
function updateEmail(response) {
var div = document.getElementById("output");
div.innerHTML = "<p>" + response + "</p>";
}
</script>
For debugging, you can use Logger.log("your text here"); then view the Logs.
function processForm(formObject) {
Logger.log('processForm ran: ' + formObject);
var response = "";
response = formObject.myEmail;
Logger.log('response: ' + response);
return response;
};
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment1</title>
<link rel="stylesheet" href="valid.css">
<script type="text/javascript" src="formValid.js"></script>
</head>
<body>
<h2>Info Grabber</h2>
<span class="required_fields">* Denotes Required Field</span>
<!--<form id = "contact_form" action="" >/-->
<form id="contact_form" action = "#" method="post" onSubmit="return validateForm(this)" >
<!-- <table> -->
<div class="name">
<div>
<label for='name'>Name<span class="red">*</span></label>
<input type='text' name='name' id='name' placeholder="First and last name" >
<div class="fixed" id="nameError">
Please enter your first and last name with a space between!</div>
</div>
</div>
<div class="address1">
<div>
<label for='address1'>Address Line 1<span class="red">*</span></label>
<input type='text' name='address1' id='address1' >
<div class="fixed" id="address1error">
Please enter your address!</div>
</div>
</div>
<div class="address2">
<div>
<label for='address2'>Address Line 2</label>
<input type='text' name='address2' id='address2'>
</div>
<div>
<label for="county">County<span class="red">*</span></label>
<select id="county" name="county">
<option value="" selected>Please select...</option>
<option value="01">Andivim
<option value="02">Armagh
<option value="03">Carlow
<option value="04">Cavan
<option value="05">Clare
<option value="06">Cork
<option value="07">Derry
<option value="08">Donegal
<option value="09">Down
<option value="10">Dublin
<option value="11">Fermanagh
<option value="12">Galway
<option value="13">Kerry
<option value="14">Kildare
<option value="15">Kilkenny
<option value="16">Laois
<option value="17">Leidivim
<option value="18">Limerick
<option value="19">Longford
<option value="20">Louth
<option value="21">Mayo
<option value="22">Meath
<option value="23">Monaghan
<option value="24">Offaly
<option value="25">Roscommon
<option value="26">Sligo
<option value="27">Tipperary
<option value="28">Tyrone
<option value="29">Waterford
<option value="30">Westmeath
<option value="31">Wexford
<option value="32">Wicklow
</select>
<div id="countyError" class="fixed">
Please select your county!</div>
</div>
</div>
<div class="gender">
<label>Gender<span class="red">*</span></label>
<input type="radio" name="gender" id="male" value="m">Male
<input type="radio" name="gender" id="female" value="f" >Female
<div id="genderError" class="fixed">
Please select your gender! </div>
</div>
<div class="preferences">
<label>Preferences<span class="red">*</span></label>
<input type="checkbox" name="color" id="red" value="r">Red
<input type="checkbox" name="color" id="green" value="g">Green
<input type="checkbox" name="color" id="blue" value="b">Blue
<div id="colorError" class="fixed">Please select a color! </div>
</div>
<div class="phone">
<label for="phone">Phone<span class="red">*</span></label>
<input type="text" id="phone" name="phone" placeholder="Eg. 0871234567">
<div id="phoneError" class="fixed">
Please enter a valid phone number with 10 digits in length! </div>
</div>
<div class="email">
<label for="email">Email<span class="red">*</span></label>
<input type="text" id="email" name="email" placeholder="example#domain.com">
<div id="emailError" class="fixed">
Please enter a valid email in the format "johndoe#domain.com"! </div>
</div>
<div class="password1">
<label for="password1">Password (6-8 characters)<span class="red">*</span></label>
<input type="password" id="password1" name="password1">
<div id="password1Error" class="fixed">
Please enter a valid password containing at least one uppercase letter and one number!</div>
</div>
<div class="password2">
<label for="password2">Verify password<span class="red">*</span></label>
<input type="password" id="password2" name="password2">
<div id="password2Error" class="fixed">
Passwords do not match, please re-enter! </div>
</div>
<div>
<label>
<input type="submit" value="SEND" id="submit">
</label>
</div>
<div>
<label>
<input type="reset" value="CLEAR" id="reset">
</label>
</div>
<!-- </table> -->
</form>
</body>
</html>
</form>
</body>
</html>
I'm newish to javascript css and HTML. I have to create a form that changes the input borders to red and display an error message when the wrong data is entered.
I have to use javascript for the validation as part of project so I can't use HTML5 'required'. When I run my program none of the errors show and when i click the submit button it clears all the fields.
I tried it in JSFiddle and got the following error which I don't understand
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': , 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': , 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': , 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': , 'help_text': '', 'name': 'js_wrap'}"}
I have tried and tried but I can't get this to work.
Any help would be greatly appreciated.
=====================================================================================
valid.css
.red {
color: red;
}
.input.error { /* for the error input text fields */
border: 1px red inset;
padding: 2px;
}
.error {
visibility: visible;
color: red;
display: inline-block;
}
/*
table {
border: 0;
}
td {
margin: 0;
padding: 3px 10px 3px 3px;
}
*/
label
{
display: inline-block;
width: 170px;
margin-top:10px;
margin-bottom:10px;
}
.colorLabel {
border: thin solid red;
}
.unColorLabel {
border: thin solid #3FE916;
}
.fixed {
visibility: hidden;
display: inline-block;
}
.required_fields {
color: red;
}
======================================================================================
formValid.js
function validateForm()
{
var name = document.getElementById("name");
if(name.length < 5 || !name.match(/[A-Za-z ]$/))
{
document.getElementById("name").className = "colorLabel";
document.getElementById("nameError").className = "error";
}
else
{
document.getElementById("name").className = "unColorLabel";
document.getElementById("nameError").className = "fixed";
}
var address1 = document.getElementById("address1");
if(address1.length === 0 || !address1.match(/[A-Za-z ]$/))
{
document.getElementById("address1").className = "colorLabel";
document.getElementById("address1Error").className = "error";
}
else
{
document.getElementById("address1").className = "unColorLabel";
document.getElementById("address1Error").className = "fixed";
}
// Return true if correct element is selected
var county= document.getElementById("county");
if(county == "-1")
{
document.getElementById("county").className = "colorLabel";
document.getElementById("countyError").className = "error";
}
else
{
document.getElementById("county").className = "unColorLabel";
document.getElementById("countyError").className = "fixed";
}
// Return true if the one of the radio buttons is checked
var gender = document.getElementsByName("gender");
var isChecked = false;
for (var i = 0; i < gender.length; i++)
{
if (gender[i].checked)
{
isChecked = true; // found one element checked
document.getElementById("genderError").className = "fixed";
break;
}
else
{
document.getElementById("genderError").className = "error";
}
}
var color = document.getElementsByName("color");
var isChecked2 = false;
for (var j = 0; j < color.length; j++)
{
if (color[j].checked)
{
isChecked2 = true; // found one element checked
document.getElementById("colorError").className = "fixed";
break;
}
else
{
document.getElementById("colorError").className = "error";
}
}
var phone = document.getElementById("phone");
if(inputValue.length != 10 || (inputValue.search(/^[0-9]+$/) == -1))
{
document.getElementById("phone").className = "colorLabel";
document.getElementById("phoneError").className = "error";
}
else
{
document.getElementById("phone").className = "unColorLabel";
document.getElementById("phoneError").className = "fixed";
}
var email = document.getElementById("email");
var atPos = email.indexOf("#");
var dotPos = email.lastIndexOf(".");
if((atPos < 1) && (dotPos < atPos + 1) && (inputValue.length < dotPos + 2))
{
document.getElementById("email").className = "colorLabel";
document.getElementById("emailError").className = "error";
}
else
{
document.getElementById("email").className = "unColorLabel";
document.getElementById("emailError").className = "fixed";
}
var password1 = document.getElementById("password1");
var allowed = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,8}$/;
var inputValue = password1.value.trim();
if(!(inputValue.value.match(allowed)))
{
document.getElementById("password1").className = "colorLabel";
document.getElementById("password1Error").className = "error";
}
else
{
document.getElementById("password1").className = "unColorLabel";
document.getElementById("password1Error").className = "fixed";
}
var password2 = document.getElementById("password2");
if(password1.value != password2.value)
{
document.getElementById("password2").className = "colorLabel";
document.getElementById("password2Error").className = "error";
}
else
{
document.getElementById("password2").className = "unColorLabel";
document.getElementById("password2Error").className = "fixed";
}
}
enter code here
I'm trying to fill 2 inputs with google autocomplete and then get google map directions asd route.
I manage to use autocomplete, but when I click in the submit button nothing happens.
I'm using this code:
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(39.57182223734374, -7.811279296875), 15);
gdir = new GDirections(map, document.getElementById("directions"));
var input = document.getElementById('tb_fromPoint');
var autocomplete = new google.maps.places.Autocomplete(input);
var input2 = document.getElementById('tb_endPoint');
var autocomplete2 = new google.maps.places.Autocomplete(input2);
setDirections();
}
function setDirections() {
var fromAddress = document.getElementById('tb_fromPoint');
var toAddress = document.getElementById('tb_endPoint');
gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "pt_PT" });
}
google.maps.event.addDomListener(window, 'load', initialize);
From :
To:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Directions service</title>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places" type="text/javascript"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(13.0524139, 80.25082459999999);
var mapOptions = {
zoom:7,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('city1').value;
var end = document.getElementById('city2').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 650px; height: 350px;"></div>
<script type="text/javascript">
function initialize1() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input1 = document.getElementById('searchTextField1');
var autocomplete = new google.maps.places.Autocomplete(input1,options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place1 = autocomplete.getPlace();
document.getElementById('city1').value = place1.name;
document.getElementById('cityLat1').value = place1.geometry.location.lat();
document.getElementById('cityLng1').value = place1.geometry.location.lng();
document.getElementById('cityy').value = place1.city_name;
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize1);
function initialize2() {
var options = {
//types: ['(cities)'],
componentRestrictions: {country: "in"}
};
var input2 = document.getElementById('searchTextField2');
var autocomplete = new google.maps.places.Autocomplete(input2, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place2 = autocomplete.getPlace();
document.getElementById('city2').value = place2.name;
document.getElementById('cityLat2').value = place2.geometry.location.lat();
document.getElementById('cityLng2').value = place2.geometry.location.lng();
initialize();
calcRoute()
});
}
google.maps.event.addDomListener(window, 'load', initialize2);
</script>
<input id="searchTextField1" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city1" name="city1" /> <br />
<input type="text" id="cityLat1" name="cityLat1" /> <br />
<input type="text" id="cityLng1" name="cityLng1" /> <br />
<input id="searchTextField2" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <br />
<input type="text" id="city2" name="city2" /> <br />
<input type="text" id="cityLat2" name="cityLat2" /> <br />
<input type="text" id="cityLng2" name="cityLng2" /> <br />
</body>
</html>