Validating a Google Apps Form with Javascript - javascript

I'm using this solution to feed inputs and image submissions from a form into a Google Sheet and Folder on Google Drive.
I need to validate a few of the fields - just requiring them to be filled out. Unfortunately, the solution I'm using uses a type="button" to submit the form instead of type="submit" and I'm not quite adept enough at Javascript to change that.
However, I found this solution for validating a form with a type="button" submit - but it's not working. With that implemented my form just does nothing - doesn't validate, doesn't submit.
This specifically is the bit of Javascript I'm struggling to get working:
//Validate Form
function() {
$("#myForm").validate({
rules: {
name: "required"
},
messages: {
name: "Please specify your name"
}
})
$('#btn').click(function() {
$("#myForm").valid();
});
};
It works fine in normal HTML in my browser - but doesn't work in Google Apps, so I'm assuming there's some comma or something in the wrong place since it seems Google has different JS requirements?
The rest of my code and a link to the sheet/form/script are below:
Form.html
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
};
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}'
//Toggle Secondary Categories
$(function() {
$(".box").not("." + this.id).hide(); $("." + this.id).show();
});
//Calculate Split
function check(split)
{
var split=document.forms[0].split.value
var amount=document.forms[0].amount.value
var tip = (amount*split)
document.forms[0].manufacturer.value=tip
var tip2 = (amount-tip)
document.forms[0].pace.value=tip2
};
//Validate Form
function() {
$("#myForm").validate({
rules: {
name: "required"
},
messages: {
name: "Please specify your name"
}
})
$('#btn').click(function() {
$("#myForm").valid();
});
};
</script>
<div id="formDiv" class="form">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
<div class="row">
<h1>Co-op Submission Form</h1>
<h2>Please fill out the form completely, including uploading any documentation associated with your co-op claim.</h2>
</div>
<h3>Your Information</h3>
<h4>Name:</h4> <input name="name" type="text" class="form-control mustHave"/><br/>
<h4>Email:</h4> <input name="email" type="text" class="form-control mustHave"/><br/>
<h3>Co-Op Information</h3>
<h4>Brand:</h4>
<select name="brand" class="form-control">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Jonsered</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
<h4>Invoice Date:</h4> <input name="date" type="text" class="form-control"/><br/>
<h4> Total Co-Op Amount</h4> <input type="text" name="amount" class="form-control"/><br />
<h4>Co-Op Split:</h4>
<input type="radio" name="split" onclick="check(this.value)" value="1">100%<br>
<input type="radio" name="split" onclick="check(this.value)" value=".5">50/50<br>
<input type="radio" name="split" onclick="check(this.value)" value=".75">75/25<br />
<input type="radio" name="split" onclick="check(this.value)" value=".25">25/75 (Dealer Pays 50%)<br />
<h4>Manufacturer Amount:</h4> <input type="text" name="manufacturer" style="border:none;font-weight:bold;"><br />
<h4>Pace Amount:</h4> <input type="text" name="pace" style="border:none;font-weight:bold;" >
<h4>Description:</h4> <input name="reason" type="text" cols="20" rows="5" class="form-control mustHave"/><br />
<h4>Co-Op Category:</h4>
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" class="form-control"/><br />
<!--Dealer Advertising-->
<div class="dealer box" style="display:none;">
<h4>Dealer Advertising:</h4>
<input type="radio" name="subcategory" value="Billboards">Billboards<br />
<input type="radio" name="subcategory" value="Logo Merch">Logo Merch (hats, shirts, pens, etc.)<br />
<input type="radio" name="subcategory" value="Magazine/Newspaper">Magazine/Newspaper<br />
<input type="radio" name="subcategory" value="Open House/Trade Show">Open House & Dealer Trade Show<br />
<input type="radio" name="subcategory" value="POP">POP (lit, posters,displays, etc)<br />
<input type="radio" name="subcategory" value="Radio">Radio<br />
<input type="radio" name="subcategory" value="PACE Trade Show">PACE Trade Show<br />
<input type="radio" name="subcategory" value="TV">TV<br />
<input type="radio" name="subcategory" value="Direct Mail">Direct Mail (post cards, flyers)<br />
<input type="radio" name="subcategory" value="Sponsorships">Sponsorships<br />
</div>
<!--Digital/Online Advertising-->
<div class="online box" style="display: none;">
<h4>Digital/Online Marketing:</h4>
<input type="radio" name="subcategory" value="CMS/Advertising">CMS/Dealer Website Advertising<br />
<input type="radio" name="subcategory" value="TRM Digital Marketing">TRM Digital Marketing (google, facebook, retargeting, demo site, youtube)
</div>
<!--Meetings and Schools-->
<div class="meetings box" style="display: none;">
</div>
<!--PACE Advertising-->
<div class="advertising box" style="display: none;">
<h4>PACE Advertising:</h4>
<input type="radio" name="subcategory" value="Billboards">Billboards<br />
<input type="radio" name="subcategory" value="Logo Merch">Logo Merch (hats, shirts, pens, etc.)<br />
<input type="radio" name="subcategory" value="POP">POP (lit, posters,displays, etc)<br />
<input type="radio" name="subcategory" value="PACE Trade Show">PACE Trade Show<br />
</div>
<!--Program Pricing Promotions-->
<div class="pricing box" style="display: none;">
<h4>Program Pricing Promotions:</h4>
<input type="radio" name="subcategory" value="Promo Prices, Discounts, Rebates - Unassigned">Promo Prices, Discounts, Rebates - Unassigned<br />
<input type="radio" name="subcategory" value="Promo Pricing">Promo Pricing<br />
<input type="radio" name="subcategory" value="Demo">Demo<br />
<input type="radio" name="subcategory" value="Fleet">Fleet<br />
<input type="radio" name="subcategory" value="Spiffs and Rebates">Spiffs and Rebates<br />
</div>
<!--PACE-to-Dealer Correspondence-->
<div class="correspondence box" style="display: none;">
<h4>PACE-to-Dealer Correspondence:</h4>
<input type="radio" name="subcategory" value="Pacesetter Catalog">Pacesetter Catalog<br />
<input type="radio" name="subcategory" value="Dealer Programs (updates, reprints)">Dealer Programs (updates, reprints)<br />
</div>
<h4>Message:</h4> <textarea name="message" class="form-control"></textarea><br/>
<h4> Supporting Documentation:</h4>
<input name="myFile1" type="file"/>
<a onclick="document.getElementById('div1').style.display='';return false;" href="">Submit More</a><br />
<div id="div1" style="display:none;margin: 15px 0;">
<input name="myFile2" type="file"/>
<a onclick="document.getElementById('div2').style.display='';return false;" href="">Submit More</a><br />
</div>
<div id="div2" style="display:none;margin: 15px 0;">
<input name="myFile3" type="file"/>
<a onclick="document.getElementById('div3').style.display='';return false;" href="">Submit More</a><br />
</div>
<div id="div3" style="display:none;margin: 15px 0;">
<input name="myFile4" type="file"/>
<a onclick="document.getElementById('div4').style.display='';return false;" href="">Submit More</a><br />
</div>
<div id="div4" style="display:none;margin: 15px 0;">
<input name="myFile5" type="file"/><br /></div>
<br />
<input type="button" value="Validate" id="btn" class="btn" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
<div class="uploading">Uploading. Please wait...</div>
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</div>
<!--Begin Footer-->
<div class="footer">
<div class="bottomStrip">
<div class="col-lg-3 col-lg-push-1">© <script type="text/javascript"> document.write(new Date().getFullYear());</script>, PACE, Inc. All rights Reserved.</div>
<div class="col-lg-4 col-lg-push-5">PACE, Inc., 739 S. Mill St., Plymouth, MI 48170-1821</div>
</div>
</div>
<!--End Footer-->
</body>
Code.gs
var submissionSSKey = '1e56M0GL6649pVW0SUwZDR8CjuyTqEwrkAUUWYVmiOpk';
var folderId = "0B3YZCO2xGxYFdHV4Q2pvY0U4d0U";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob1 = theForm.myFile1;
var fileBlob2 = theForm.myFile2;
var fileBlob3 = theForm.myFile3;
var fileBlob4 = theForm.myFile4;
var fileBlob5 = theForm.myFile5;
var folder = DriveApp.getFolderById(folderId);
var doc1 = folder.createFile(fileBlob1);
var doc2 = folder.createFile(fileBlob2);
var doc3 = folder.createFile(fileBlob3);
var doc4 = folder.createFile(fileBlob4);
var doc5 = folder.createFile(fileBlob5);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var email = template.email = theForm.email;
var brand = template.brand = theForm.brand;
var date = template.date = theForm.date;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var manufacturer = template.manufacturer = theForm.manufacturer;
var pace = template.pace = theForm.pace;
var reason = template.reason = theForm.reason;
var category = template.category = theForm.category;
var subcategory = template.subcategory = theForm.subcategory;
var message = template.message = theForm.message;
var fileUrl1 = template.fileUrl1 = doc1.getUrl();
var fileUrl2 = template.fileUrl2 = doc2.getUrl();
var fileUrl3 = template.fileUrl2 = doc3.getUrl();
var fileUrl4 = template.fileUrl2 = doc4.getUrl();
var fileUrl5 = template.fileUrl2 = doc5.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 17).setValues([[name, email,brand,date,amount,split,manufacturer,pace,reason,category,subcategory,message,fileUrl1,fileUrl2,fileUrl3,fileUrl4,fileUrl5]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
Link to Sheet

Based from this SO question, in type="button" buttons will not submit a form and they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application while type="submit" buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.
I suggest to use type="submit" instead of type="button" since it will submit the form when clicked when it's inside a form element as stated in this documentation.
Hope this helps!

Related

passing a string variable in a javascript function

I am creating a menu list with php. I want the user to change name and the discount variable in the list. So here is an image of the list:list with items, so for each list item and subitems, there's a button which must open a popup and pass the variables belonging to that listitem, like names and discount variable into the form input field, so the user can adjust it from the old value. I use javascript to open and close the form, and want it also to put the php variables (obtained from a database) into that form. So here is my piece of code:
javascript:
<script>
function updatepopup(**$name**, $discount){
document.getElementById("updatedata").style.display = "block";
document.getElementById("fnaam").value = **$name**";
document.getElementById("fkort").value = $discount;
}
function closeform(){
document.getElementById("updatedata").style.display = "none";
}
</script>
php:
<ol class='tree'> ";
if ($currLevel == $prevLevel) echo " ";
echo '
<li>
<label for="subfolder2">'.$category['name'].'</label>
<label> '.$category['discount'].'%</label>
<input type="checkbox" name="subfolder2">
<form id="updatedata" method="POST">
<label for="fnaam">Naam: </label>
<input type="text" id="fnaam" name="fnaam" value="'.$category['name'].'">
<label for="fkort">Korting</label>
<input type="number" id="fkort" name="fkort" value="'.$category['discount'].'">
<button id="closebutton" onclick="closeform()">X</button>
<button type= "submit"> </button>
</form>
<button onclick="updatepopup()"><i class="fa-solid fa-pen-to-square"></i></button>
';
if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }
$currLevel++;
createTreeView ($array, $categoryId, $currLevel, $prevLevel);
$currLevel--;
}
}
if ($currLevel == $prevLevel) echo "<li><button>+</button></li></li>
</ol>";
}
?>
So I have read many solutions to pass a string to a javascript function but not a single one would help. I only get something like that done with numbers, but I also want to sent a string into that input field.
So this is what I want to get: what I want
You're trying to mix PHP with JavaScript, which should be avoided if possible. There are other ways to pass PHP values to JavaScript, like setting them as HTML attributes.
My approach would be to create a <form> element for each list item and output your PHP $category values in hidden <input /> elements.
<!-- Start list -->
<ol class='tree'>
<li>
<form class="js-update-data">
<label for="subfolder2"><?= $category['name']; ?></label>
<span><?= $category['discount']; ?>%</span>
<input type="checkbox" name="subfolder2">
<input type="hidden" name="name" value="<?= $category["name"]; ?>"/>
<input type="hidden" name="discount" value="<?= $category["discount"]; ?>" />
<button type="submit"><i class="fa-solid fa-pen-to-square"></i></button>
</form>
<!-- Nested list -->
<ol class='tree'>
<li>
<form class="js-update-data">
<!-- Structure for every list item.. -->
</form>
</li>
</ol>
</li>
</ol>
<!-- End list -->
<!-- Form to show/hide & update -->
<form id="updatedata" method="POST">
<label for="fnaam">Naam: </label>
<input type="text" id="fnaam" name="fnaam" value="">
<label for="fkort">Korting</label>
<input type="number" id="fkort" name="fkort" value="">
<button type="button" id="closebutton">X</button>
<button type="submit"> </button>
</form>
Then listen for submit events on these forms. When a form gets submitted, make sure the preventDefault() method on the event is called. This will prevent a reload of the page and allows you to write your own behavior.
Extract the values from the submitted form and pass them to your updatepopup function.
const forms = document.querySelectorAll('.js-update-data');
for (const form of forms) {
form.addEventListener('submit', event => {
event.preventDefault();
const formData = new FormData(event.target);
const name = formData.get('name');
const discount = formData.get('discount');
updatepopup(name, discount);
});
}
const closeButton = document.getElementById("closebutton");
closeButton.addEventListener('click', closeform);
function updatepopup(name, discount){
document.getElementById("updatedata").display = "block";
document.getElementById("fnaam").value = name;
document.getElementById("fkort").value = discount;
}
function closeform(){
document.getElementById("updatedata").style.display = "none";
}
Runnable example
This example runs with pre-filled values. The only job you have is to set the values in the right spot.
const forms = document.querySelectorAll('.js-update-data');
for (const form of forms) {
form.addEventListener('submit', event => {
event.preventDefault();
const formData = new FormData(event.target);
const name = formData.get('name');
const discount = formData.get('discount');
updatepopup(name, discount);
});
}
const closeButton = document.getElementById("closebutton");
closeButton.addEventListener('click', closeform);
function updatepopup(name, discount){
document.getElementById("updatedata").hidden = false;
document.getElementById("fnaam").value = name;
document.getElementById("fkort").value = discount;
}
function closeform(){
document.getElementById("updatedata").hidden = true;
}
form[hidden] {
display: none;
}
<!-- Start list -->
<ol class='tree'>
<li>
<form class="js-update-data">
<label for="subfolder2">Test 1</label>
<span>25%</span>
<input type="checkbox" name="subfolder2">
<input type="hidden" name="name" value="Test 1"/>
<input type="hidden" name="discount" value="25" />
<button type="submit"><i class="fa-solid fa-pen-to-square"></i>edit</button>
</form>
<!-- Nested list -->
<ol class='tree'>
<li>
<form class="js-update-data">
<label for="subfolder2">Test 2</label>
<span>13%</span>
<input type="checkbox" name="subfolder2">
<input type="hidden" name="name" value="Test 2"/>
<input type="hidden" name="discount" value="13" />
<button type="submit"><i class="fa-solid fa-pen-to-square">edit</i></button>
</form>
</li>
</ol>
</li>
<li>
<form class="js-update-data">
<label for="subfolder2">Test 4</label>
<span>80%</span>
<input type="checkbox" name="subfolder2">
<input type="hidden" name="name" value="Test 4"/>
<input type="hidden" name="discount" value="80" />
<button type="submit"><i class="fa-solid fa-pen-to-square"></i>edit</button>
</form>
<!-- Nested list -->
<ol class='tree'>
<li>
<form class="js-update-data">
<label for="subfolder2">Test 3</label>
<span>50%</span>
<input type="checkbox" name="subfolder2">
<input type="hidden" name="name" value="Test 3"/>
<input type="hidden" name="discount" value="50" />
<button type="submit"><i class="fa-solid fa-pen-to-square"></i>edit</button>
</form>
</li>
</ol>
</li>
</ol>
<!-- End list -->
<!-- Form to show/hide & update -->
<form id="updatedata" method="POST" hidden>
<label for="fnaam">Naam: </label>
<input type="text" id="fnaam" name="fnaam" value="">
<label for="fkort">Korting</label>
<input type="number" id="fkort" name="fkort" value="">
<button type="button" id="closebutton">X</button>
<button type="submit"> </button>
</form>

The first radio button's value is always being sent

I have (4) radio buttons and submit button:
<form class="addrecipe-form" method="GET">
<div class="addrecipe-form-header-row">
<div>
<input type="radio" class="recipe-type-button" id="breakfast" name="recipe-type" value="breakfast" />
<label for="breakfast" class="recipe-type-label">breakfast</label>
</div>
<div>
<input type="radio" class="recipe-type-button" id="appetizer" name="recipe-type" value="appetizer" />
<label for="appetizer" class="recipe-type-label">appetizer</label>
</div>
<div>
<input type="radio" class="recipe-type-button" id="entree" name="recipe-type" value="entree" />
<label for="entree" class="recipe-type-label">entree</label>
</div>
<div>
<input type="radio" class="recipe-type-button" id="dessert" name="recipe-type" value="dessert" />
<label for="dessert" class="recipe-type-label">dessert</label>
</div>
</div>
<button class="addrecipe-button" type="submit" name="recipe-submit"></button>
</form>
Here's the javascript:
var addRecipeForm = document.querySelector(".addrecipe-form");
var recipe_entry;
addRecipeForm.addEventListener('submit', function(e) {
e.preventDefault();
recipe_entry = {
type : document.querySelector(".recipe-type-button").value)
}
console.log(recipe_entry.type)
I just can't figure out why I keep getting the first radio button's value instead of the one I'm clicking on. Can someone enlighten me, pls?
The "document.querySelector()" function returns the FIRST occurrence of that matching query selector.
I would use a for loop and "document.getElementsByClassName()" to check each radio button's value, and only save the state if it is selected.
Like this:
addRecipeForm.addEventListener('submit', function(e) {
e.preventDefault();
for(var i=0;i<document.getElementsByClassName("recipe-type-button").length){
if(document.getElementsByClassName("recipe-type-button")[i].checked){
recipe_entry = {
type : document.getElementsByClassName("recipe-type-button")[i].value
}
}
}
console.log(recipe_entry.type)
}
Try..
type: document.querySelector(".recipe-type-button:checked").value
.. to get the selected value.
Full script:
<html>
<form class="addrecipe-form" method="GET">
<div class="addrecipe-form-header-row">
<div>
<input
type="radio"
class="recipe-type-button"
id="breakfast"
name="recipe-type"
value="breakfast"
/>
<label for="breakfast" class="recipe-type-label">breakfast</label>
</div>
<div>
<input
type="radio"
class="recipe-type-button"
id="appetizer"
name="recipe-type"
value="appetizer"
/>
<label for="appetizer" class="recipe-type-label">appetizer</label>
</div>
<div>
<input
type="radio"
class="recipe-type-button"
id="entree"
name="recipe-type"
value="entree"
/>
<label for="entree" class="recipe-type-label">entree</label>
</div>
<div>
<input
type="radio"
class="recipe-type-button"
id="dessert"
name="recipe-type"
value="dessert"
/>
<label for="dessert" class="recipe-type-label">dessert</label>
</div>
</div>
<button class="addrecipe-button" type="submit" name="recipe-submit">
Magic
</button>
</form>
<script>
var addRecipeForm = document.querySelector(".addrecipe-form");
var recipe_entry;
addRecipeForm.addEventListener("submit", function (e) {
e.preventDefault();
recipe_entry = {
type: document.querySelector(".recipe-type-button:checked").value,
};
console.log(recipe_entry.type);
});
</script>
</html>

Js if active then input required

I have this radio form which make active a specific input type text when the radio is checked.
I want the input that is active to be required to submit the form but i'm pretty bad in JS right now. If someone could help it would be trully appreciated thx u !
Here is my code :
<div class=" bottommargin-sm">
<label>Platforme<small class="text-danger">*</small> : </label>
<div class="btn-group btn-group-toggle nav" data-toggle="buttons">
<a href="#attending-tab-1" class="btn btn-outline-youtube px-4 t600 ls0 nott si-youtube flex-fill" data-toggle="tab">
<input type="radio" name="choice-platform" required value="0"><i class="icon-youtube"></i> Youtube
</a>
<a href="#attending-tab-2" class="btn btn-outline-soundcloud px-4 t600 ls0 nott si-soundcloud flex-fill" data-toggle="tab">
<input type="radio" name="choice-platform" id="template-wedding-attending-no" value="1" required><i class="icon-soundcloud1"></i> Soundcloud
</a>
</div>
<div class="tab-content">
<div class="tab-pane bg-light p-4 mt-2" id="attending-tab-1">
<div class="row">
<input type="text" name="platform1" class="form-control">
</div>
</div>
<div class="tab-pane bg-light p-4 mt-2" id="attending-tab-2">
<div class="row">
<input type="text" name="platform2" class="form-control">
</div>
</div>
</div>
</div>
Are you looking to make an HTML form field required based on a user select option. Then hope this will work for you.
function updateRequirement() {
var form = document.forms[0];
var radios = document.getElementsByName('option');
var selectedValue;
for( i = 0; i < radios.length; i++ ) {
if( radios[i].checked ) {
selectedValue = radios[i].value;
}
}
if(selectedValue === 'yes') {
document.getElementById('non-mandatoryfield').required = true;
} else {
document.getElementById('non-mandatoryfield').required = '';
}
}
<form>
Make optional field mandatory <br />
<div id="options">
<input type="radio" name="option" value="yes" onchange="updateRequirement()"> Yes<br>
<input type="radio" name="option" value="no" onchange="updateRequirement()"> No<br>
</div>
<br />
First name: (Required Always)<br />
<input type="text" required name="firstname" value="" />
<br />
Last name: (Optional Always)<br />
<input type="text" id="non-mandatoryfield" name="lastname" value="" />
<br /><br />
<input type="submit" value="Submit" />
</form>
This is the js code
$("#template-wedding-attending-no").on("checked", function () {
$("#attending-tab-1").prop(true);
})

how to make a picture become interactive with buttons?

*[1]: https://i.stack.imgur.com/WmJv1.jpg
Hi everyone, I would like to thank any help in advance.
I'm quite new to this whole coding world, so i have been given a project to do. I have already set up the HTML file to how I want it to look and etc.... The only problem I'm currently having is, I'm not sure how to use javascript to make the buttons work and store the information. Would anyone share some light on how to get the beds to become interactive? I guess once I can get the beds to be interactive with the buttons I can somewhat play around with the rest and see how I get on.
<!DOCTYPE html>
<html>
<head>
<title> Ward Beds </title>
<style>
body{ border: groove 4px; }
</style>
</head>
<body bgcolor="LIGHTSKYBLUE">
<form
<div
</div>
<p>
</p>
<img id="Bed1" src="bedleftempty.gif" /> <img id="Bed5" src="BedREmpty.gif" />
<div
</div>
<img id="Bed2" src="bedleftempty.gif" /> <img id="Bed6" src="BedREmpty.gif" />
<div
</div>
<img id="Bed3" src="bedleftempty.gif" /> <img id="Bed7" src="BedREmpty.gif" />
<div
</div>
<img id="Bed4" src="bedleftempty.gif" /> <img id="Bed8" src="BedREmpty.gif" />
<div
</div>
<center>
<input id="btnAdmit" type="button" value="Admit"
onclick="btnAdmit_OnClick()" > <input id="btnDischarge" type="button" value="Discharge"
onclick="btnDischarge_OnClick()" />
<div
</div>
<p>
<input id="btnMale" type="button" value="Male"
onclick="btnMale_OnClick()" />
<div
</div>
<input id="btnFemale" type="button" value="Female"
onclick="btnFemale_OnClick()" />
<div
</div>
<input id="btnUnknown" type="button" value="Unknown"
onclick="btnUnknown_OnClick()" />
<div
</div>
</p>
<p>
<label>First Name</label> <input type="text" id="myText" value=" " /> <label>Last Name</label> <input type="text" id="myText" value=" " />
</p>
<label> Location of Surgery</label>
<div
</div>
<input type="checkbox" name="LeftArm" value="LeftLeg"> LeftArm<br> />
<div
</div>
<input type="checkbox" name="RightArm" value="RightLeg" > RightArm<br> />
<div
</div>
<input type="checkbox" name="LeftLeg" value="LeftLeg"> LeftLeg<br> />
<div
</div>
<input type="checkbox" name="RightLeg" value="RightLeg"> RightLeg<br> />
<div
</div>
<input type="checkbox" name="Unknown" value="Unknown"> Unknown<br> />
<div
</div>
<input type="checkbox" name="Head" value="Head"> Head<br> />
<div
</div>
<input type="checkbox" name="Chest" value="Chest"> Chest<br> />
<div
</div>
<input type="checkbox" name="Abdomen" value="Abdomen"> Abdomen<br> />
<div
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
<script language="javascript">
Well my advise advice is to start with simple HTML tutorials.
Because there is a lot of invalid html and some invalid css.
function GetId(id) { return document.getElementById(id) }
// Store information for eatch bed in an array
var beds = [],
// Stores amount of max beds
maxBeds = 8,
// Get beds paragraph
htmlBeds = GetId("beds");
// Loops the amount of maxBeds by increasing i eatch time
for (let i = 0; i < maxBeds; i++) {
// Add an empy bed.
htmlBeds.innerHTML += '<img id="Bed'+(i+1)+'" src="http://mtdef.com/Lib/Img/StackOverflow/bed.png" onclick="bed_Onclick('+i+')"> ';
if (i % 2) htmlBeds.innerHTML += '<br>';
}
//functions you request from the html
function btnAdmit_OnClick() {
let gender, fullName, surgeryLocation = "";
if (GetId('btnMale').checked) gender = "Male";
if (GetId('btnFemale').checked) gender = "Female";
if (GetId('btnUnknown').checked) gender = "Unknown";
fullName = GetId('FirstName').value + " " + GetId('LastName').value;
// Loop 8 times over the Location of Surgery by increasing i eatch time.
for (let i = 0; i < 8; i++) {
let LoS = GetId("LoS"+i);
if (LoS.checked) surgeryLocation += LoS.value + " ";
}
//push patient object to array
beds.push({
gender:gender,
fullName:fullName,
surgeryLocation:surgeryLocation
});
}
//removes last added patient
function btnDischarge_OnClick() {
beds.splice(-1,1);
}
//shows patients stats
function bed_Onclick(bedId) {
if (beds[bedId] === undefined) console.log("bed: " + (bedId+1) +
"\nis empty");
else console.log("bed: " + (bedId+1) +
"\ngender: " + beds[bedId].gender +
"\nfull name: " + beds[bedId].fullName +
"\nlocation of surgery: " + beds[bedId].surgeryLocation
);
}
body {
background-color: lightblue;
border: groove 4px;
}
<center>
<!-- Get filled by JavaScript -->
<p id=beds></p>
<input id="btnAdmit" type="button" value="Admit" onclick="btnAdmit_OnClick()" >
<input id="btnDischarge" type="button" value="Discharge" onclick="btnDischarge_OnClick()" >
<p>
<input id="btnMale" type="radio" name="gender" value="Male">
<label for="btnMale">Male</label><br>
<input id="btnFemale" type="radio" name="gender" value="Female">
<label for="btnFemale">Female</label><br>
<input id="btnUnknown" type="radio" name="gender" value="Unknown" checked="checked">
<label for="btnUnknown">Unknown</label><br>
</p>
<p>
<label>First Name</label>
<input type="text" id="FirstName" value="John"> <br>
<label>Last Name</label>
<input type="text" id="LastName" value="Doe">
</p>
<label> Location of Surgery</label><br>
<input type="checkbox" id="LoS0" value="LeftArm"> LeftArm<br>
<input type="checkbox" id="LoS1" value="RightArm" > RightArm<br>
<input type="checkbox" id="LoS2" value="LeftLeg"> LeftLeg<br>
<input type="checkbox" id="LoS3" value="RightLeg"> RightLeg<br>
<input type="checkbox" id="LoS4" value="Unknown"> Unknown<br>
<input type="checkbox" id="LoS5" value="Head"> Head<br>
<input type="checkbox" id="LoS6" value="Chest"> Chest<br>
<input type="checkbox" id="LoS7" value="Abdomen"> Abdomen<br>
<input type="submit" value="Submit">
</center>
I hope that the comments are enough for you
one problem that might be causing you to not having stuff to work is that, in the example code you gave, you haven`t close the starting div tags and a couple over tags properly.
you have put ... that should help but for the button it seems that you have done it right but in your js file or in the script tag you just put
Female_OnClick() {
what you want it to do
}
try closing all the tags properly, and try that javascript thing aswell and if it still doesnt work tell me and i may be able to help...

Javascript hide/show questions depending on user input values

I am trying to hide and/or show form elements when a user selects certain values.
For example, if the user selects "yes" to the consent question, I need it to show a few questions, However, if they change their response to the consent question, I need it to hide those questions.
Here is what I have come up with so far...
$(document).ready(function () {
var input = document.getElementById('consent');
var consent_responses = [{ "0": hideConsent },{ "1": showConsent }];
input.addEventListner('click', function () {
var consent_response;
if (consent_responses[this.value]) {
content_response = consent_responses[this.Function()]
}
else {
content_response = consent_responses[this.Function]
}
});
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
function hideConsent(){
$("#date").hide(),
$("#referrer").hide(),
$("#f_name").hide(),
$("#phone_num").hide(),
$("#leave_msg").hide(),
$("#email").hide(),
}; });
Fiddle here: http://jsfiddle.net/7jX47/1/
You could do it like this: JSFiddle
Basically I only fixed a few typos (did you actually try your code before you posted here?) and added event listeners to the radio buttons with
document.getElementById(...).addEventListener(...)
I also gave your radio buttons unique IDs.
This can be simplified:
var input = document.getElementById('consent');
// Let's use the value as key, and the functions as values
var consent_responses = {
"0" : hideConsent,
"1" : showConsent
};
input.addEventListener("click", function () {
// Get the appropriate function given the value, and invoke it
consent_responses[this.value]();
});
function hideConsent() {
// ...
}
function showConsent() {
// ...
}
It's better to envelop your questions (that needs to be hidden) by a div with a class ".hidden" or style "display: none;". And simplify your code by simply asking that div to show() or hide() when needed.
Like so:
<form id="screening">
<div class="col-md-12 col-sm-12 col-xs-12 nopad" id="create">
<div class="form-group text-center">
<b>Do you agree to answer the screening questions?</b><br />
<div class="radio" id="consent">
<label>
<input type="radio" name="consent" id="consent" value="1">
Yes, I consent
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="consent" id="consent" value="0">
No, I do not consent
</label>
</div>
</div>
<!-- simplify by using this -->
<div id="questions" style="display: none;">
<div class="form-group" id="date">
<label for="date">What is today's date?</label>
<input type="date" class="form-control" id="date" name="date" />
</div>
<div class="form-group" id="referrer">
<label for="referrer">How did you hear about us/our studies?</label>
<select class="form-control" name="referrer" id="referrer">
<option></option>
<option value="1">Flyers</option>
<option value="2">Print Media</option>
<option value="3">A friend</option>
<option value="4">Online (e.g., Craigslist)</option>
<option value="5">Other</option>
</select>
</div>
<div class="form-group" id="other_explain">
<label for="other_explain">Please specify other source.</label>
<textarea class="form-control" rows="3" id="other_explain" name="other_explain"></textarea>
</div>
<div class="form-group" id="f_name">
<label for="f_name">What is your first name?</label>
<input type="text" class="form-control" id="f_name" name="f_name" />
</div>
<div class="form-group" id="phone_num">
<label for="phone_num">What is a phone number at which you can be contacted? </label>
<input type="tel" class="form-control" id="phone_num" name="phone_num" />
</div>
<div class="form-group" id="leave_msg">
<label for="leave_msg">If we call and you are not available, may we leave a message?</label><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="1">
Yes
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="0">
No
</label>
</div>
</div>
<div class="form-group" id="email">
<label for="email">What is an e-mail at which you can be contacted?</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
</div>
</div>
</form>
and in your javascript instead of using this:
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
you use:
function showConsent(){
$("#questions").show(),
};

Categories

Resources