Adding elements dynamically - javascript

I'm trying to add elements dynamically through javascript but whenever I try opening up the page they appear for a split second then disappear
I take a number of process from the input tag and run a loop to create each element individually
I tried removing everything from the event and only call a function which I placed the code in but didn't work
const numberOfProcesses = document.getElementById("numberOfProcesses").value;
const timeQuantum = document.getElementById("timeQuantum").value;
const start = document.getElementById("start");
const processDiv = document.getElementById("processDiv");
const burstDiv = document.getElementById("burstDiv");
start.addEventListener("click", (event) => {
for (let i = 0; i < numberOfProcesses; i++) {
let pLabel = document.createElement("label");
pLabel.setAttribute("id", `process ${i}`);
pLabel.innerText = `Process ${i}`;
let pInput = document.createElement("input");
pInput.setAttribute("type", "number");
pInput.setAttribute("id", `process ${i}`);
let bLabel = document.createElement("label");
bLabel.setAttribute("id", `burstTime ${i}`);
bLabel.innerText = `Burst Time ${i}`;
let bInput = document.createElement("input");
bInput.setAttribute("type", "number");
bInput.setAttribute("id", `burstTime ${i}`);
processDiv.appendChild(pLabel);
processDiv.appendChild(pInput);
burstDiv.appendChild(bLabel);
burstDiv.appendChild(bInput);
console.log(pLabel, pInput, bLabel, bInput);
}
});
<form action="">
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button id="start">Start</button>
</form>
</section>
<br /><br />
<section>
<form action="">
<div id="processDiv">
<label for="process0">P0</label>
<input type="number" name="process" id="process0" />
</div>
<div id="burstDiv">
<label for="burstTime0">Burst Time</label>
<input type="number" name="burst time" id="burstTime0" />
</div>
<button id="excute">Execute</button>
</form>

Remove action="" and set type attribute to button if nothing is submitted. The behaviour you describe is due to the form being submitted.
Do like this and you can see you console log for other errors:
<form>
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button type="button" id="start">Start</button>
</form>

Related

TypeError: Cannot set properties of undefined (setting 'checked') in javascript

<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button></button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
<script src="./main.js"></script>
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i< 4; i++){
inputlist[(i+save)%14].checked = true;
}
num++;
if(save-1 != -1){
if(inputlist[(save-1)%14].checked == true){
inputlist[(save-1)%14].checked =false;
}
}
save++;
});
When I run the code, it doesn't work any more than 7-8 clicks.
When you enter the link in the body, the first input element should behave like the image that appears.
But I get the error TypeError: Cannot set properties of undefined (setting 'checked') and it doesn't work anymore.
Why?
You have 13 inputs so it should be mod 13 not 14.
Check the snippet below
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i < 4; i++){
inputlist[(i + save) % 13].checked = true;
}
num++;
if(save - 1 !== -1){
if(inputlist[(save - 1) % 13].checked === true){
inputlist[(save - 1) % 13].checked = false;
}
}
save++;
});
<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button>Move</button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
Looking at your code, you're using %14, but you only have 12 input elements on the page. When the code is running through the loop you run out of elements. The solution is to either change your %14 to %12 or to add in an additional two input elements.
The other option if you're going to add checkboxes would be to use %inputlist.length. This would avoid needing to count how many input elements in your html file.

how to fix hook to set state in React JS?

I am trying to have a user set a function variable with an input number. I have a form they enter a number into, which needs to set the col const up top.
So far, i am using a simple hook, and col is being set (i console logged it), but its not producing the desired array. Im thinking its something getting messed up in the toggling at the bottom of the code.
function DataFrame(){
const [toggle, setToggle] = React.useState(false);
const [col, setCol] = useState(0)
var element = <li class="element"/>
var row = 3
var arr = []
var i
for (i = 0; i<row; i++){
arr.push(element)
}
const Element = () => <li className="element" />;
console.log(col)
return (
<div>
<div >
<div style={{fontFamily:'PressStart2P',opacity:'45%', width:'360px',
position:'absolute',left:'36px', top: '160px',color:'rgb(143, 0, 145)'}}>
</div>
<div >
<h1 class="dfHeader" style={{left:'30px'}}>
DataFrames :<br></br></h1>
<h1 class='dfHeader2'style={{top:'150px',left:'30px'}}>
constructor</h1>
<div class="codeBorder" style={{scrollbarColor:'#6a00ff'}}>
<div class="textbox" style={{width:'180px'}}>
<p class="instructions"></p>
<p class="instructions2"></p>
<p class="instructions3">
<form class="codeForm">
<label>
enter dimensions:
<input type="number" name="dimension" onKeyUp=
{e => setCol(e.target.value)} />
</label>
<input class='goButton' type="submit" value="run" />
</form>
<br/><br/></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form></p>
<p class="instructions3">
<form class="codeForm">
<label>
input code:
<input type="number" name="dimension" />
</label>
<input class='goButton' type="submit" value="run" />
</form> </p>
</div>
</div>
<div class="btnConsole">
<button class="dfButton" onClick={()=>setToggle( (prev) => (!prev) )}>
</button>
</div>
</div>
<div class="monitor"style={{}}>
<div class="superScreen">
<div class="screenDiv" >
<div id="subScreen" class="subScreen">
{[...Array(col).keys()].map(ul => (
<ul key={ul}>
{toggle &&
[...Array(row).keys()].map(
li => <Element key={li} />)}
</ul>
))}
</div>
</div>
</div>
</div>
<br/>
</div>
</div>
)
}
export default DataFrame;
ReactDOM.render(<DataFrame />, document.getElementById('root'));
Any help is appreciated as always!
onKeyUp={e => setCol(e.target.value)}
this is the cause of your problem. e.target.value is a string, you are setting col equal to a string. Consequently, [...Array(col).keys()] gives you an array of length 1.
const col = '5';
console.log([...Array(col).keys()]);
Change
onKeyUp={e => setCol(e.target.value)}
to
onKeyUp={e => setCol(Number(e.target.value))}

adding click events to divs to change hidden input values

I am trying to get two divs to act as checkboxes (so that users can select 0 or all) that will influence hidden input values for a total that starts at 0. I am targetting the clicked divs by toggling a bootstrap color class to show user which has been chosen and - based on that class - add values to the hidden total input values below. I can get the totals to change outright, but I am trying to add to and subtract from the totals based on what is clicked/unclicked. Right now my code is returning an "Uncaught TypeError: Cannot set property 'value' of null". Any help you can give will be greatly appreciated!
$(document).ready(function() {
$('.select-class').on('click', function() {
//toggle clicked divs to show what's been selected
$(this).toggleClass('color');
//add values to total(0) if divs are clicked (have color class)
if (this.classList.contains('color')) {
//add1:
var addTotal1 = Number(document.getElementsByName('total1').value);
var addSingle1 = Number(document.getElementById(this.id.toString() + 'add1').value);
addTotal1 += addSingle1;
document.getElementById('totaladd1').value = addTotal1.toString();
//add2:
var addTotal2 = Number(document.getElementsByName('total2').value);
var addSingle2 = Number(document.getElementById(this.id.toString() + 'add2').value);
addTotal2 += addSingle2;
document.getElementById('totaladd2').value = addTotal2.toString();
//add3:
var addTotal3 = Number(document.getElementsByName('total3').value);
var addSingle3 = Number(document.getElementById(this.id.toString() + 'add3').value);
addTotal3 += addSingle3;
document.getElementById('totaladd3').value = addTotal3.toString();
}
//Subtract values if divs are unclicked (don't have color class)
if (!this.classList.contains('color')) {
//add1:
var addTotal1 = Number(document.getElementsByName('total1').value);
var addSingle1 = Number(document.getElementById(this.id.toString() + 'add1').value);
addTotal1 -= addSingle1;
document.getElementById('totaladd1').value = addTotal1.toString();
//add2:
var addTotal2 = Number(document.getElementsByName('total2').value);
var addSingle2 = Number(document.getElementById(this.id.toString() + 'add2').value);
addTotal2 -= addSingle2;
document.getElementById('totaladd2').value = addTotal2.toString();
//add3:
var addTotal3 = Number(document.getElementsByName('total3').value);
var addSingle3 = Number(document.getElementById(this.id.toString() + 'add3').value);
addTotal3 -= addSingle3;
document.getElementById('totaladd3').value = addTotal3.toString();
}
})
});
<div class="row p-lg-5">
<div id="div1" class="select-class">
<p>Content</p>
<!--hidden values-->
<div class="d-none">
<input type="number" class="add1" id="div1add1" value="1" />
<input type="number" class="add2" id="div1add2" value="45" />
<input type="number" class="add3" id="div1add3" value="4" />
</div>
</div>
<div id="div2" class="select-class">
<p>Content</p>
<!--hidden values-->
<div class="d-none">
<input type="number" class="add1" id="div2add1" value="3" />
<input type="number" class="add2" id="div2add2" value="20" />
<input type="number" class="add3" id="div2add3" value="3" />
</div>
</div>
</div>
<!--hidden totals-->
<div class="d-none">
<input id="totaladd1" type="number" name="total1" value="0" />
<input id="totaladd2" type="number" name="total2" value="0" />
<input id="totaladd3" type="number" name="total3" value="0" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Set your add inputs as disabled by default
Add a data-total="" to every total input. Inside the data place the add-inputs-pairs selector i.e: ".add_1" etc...
Toggle class on click and perform a search for the non disabled add inputs, reducing their values to an accumulated number. Set that number as the iterating total input value
jQuery(function($) {
function calculateTot() {
$('[data-total]').each(function() {
const pair = $(this.dataset.total).not(':disabled').get();
$(this).val(pair.reduce((n, el) => (n += +el.value, n), 0))
});
}
$('.select-class').on('click', function() {
$(this).toggleClass('is-selected');
$(this).find('input').prop('disabled', !$(this).is('.is-selected'));
calculateTot();
}).find('input').prop('disabled', true); // Make inputs disabled by default
calculateTot(); // Calculate also on DOM ready
});
.select-class {cursor:pointer; padding:8px; border-radius:1em; border:1px solid #000;}
.is-selected {background:#0bf;}
.d-none {display:none;}
<div class="row p-lg-5">
<div id="div1" class="select-class">
Content 1 - Select me
<div class="d-none">
<input type="number" class="add_1" value="1" />
<input type="number" class="add_2" value="45" />
<input type="number" class="add_3" value="4" />
</div>
</div>
<div id="div2" class="select-class">
Content 2 - Select me
<div class="d-none">
<input type="number" class="add_1" value="3" />
<input type="number" class="add_2" value="20" />
<input type="number" class="add_3" value="3" />
</div>
</div>
</div>
<div> <!-- class="d-none" -->
<input data-total=".add_1" type="number" name="total1" />
<input data-total=".add_2" type="number" name="total2" />
<input data-total=".add_3" type="number" name="total3" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

HTML Form - similar input groups as an array of objects

So I have a form with two identical group of inputs that represent education info. There could be more than two as I want to include a button to create a new group so the user can put all his education background like in LinkedIn.
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
</form>
Now, if I use the FormData API to get the form data like this:
for(let entry of formData.entries()){
console.log(entry);
}
I get the following output:
(2) ["institutionName", "Harvard"]
(2) ["courseName", "Web Development"]
(2) ["startDate", "2000-11"]
(2) ["endDate", "2008-11"]
(2) ["institutionName", "Oxford"]
(2) ["courseName", "Business Management"]
(2) ["startDate", "2009-10"]
(2) ["endDate", "2010-05"]
What I want to achieve is to get the output in an organized way, like this:
education:[
{
institutionName:"Harvard",
courseName:"Web Development",
startDate:"2000-11",
endDate:"2008-11"
},
{
...
}
]
So I'm interested in knowing the best approach to achieve this. Thanks in advance for any help!
It does not make sense to have two equal forms, with one being sufficient.
In addition to the form you should have a list that shows each item added.
It's what I recommend.
Not sure whether this is the best approach, but you can achieve the desired structure like this:
const formCV = document.querySelector('#formCV');
const formData = new FormData(formCV);
function groupEducationData(inputGroupSize = 4) {
const result = [];
let educationObj = null;
let counter = 0;
for (const entry of formData.entries()) {
// Since the counter is divisible by the number of inputs in a group
// only if one form group finishes. And when one form group finishes,
// we need to add the object into the result array
if (counter % inputGroupSize === 0) {
// if this is the first iteration, the educationObj is null and
// we don't want to add it to the result array yet
// we only add the educationObj to the result array if it is
// an object containing the education info
if (educationObj) result.push(educationObj);
// initialize the educationObj at the start
// and after one form finishes
educationObj = {};
}
// add entry[0] as key to the object (e.g. 'institutionName')
// with the value of entry[1] (e.g. 'Harvard')
educationObj[entry[0]] = entry[1];
counter++;
}
return result.concat(educationObj);
}
console.log(groupEducationData());
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Harvard">
</div>
<div>
<input type="text" name="courseName" value="Web Development">
</div>
<div>
<input type="month" name="startDate" value="2000-11">
</div>
<div>
<input type="month" name="endDate" value="2008-11">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName" value="Oxford">
</div>
<div>
<input type="text" name="courseName" value="Business Management">
</div>
<div>
<input type="month" name="startDate" value="2009-10">
</div>
<div>
<input type="month" name="endDate" value="2010-05">
</div>
</div>
</div>
</form>
You can try FormData.getAll() and iterate over each group entry.
const institutionNames = formData.getAll('institutionName');
const courseNames = formData.getAll('courseName');
...
const educations = [];
for (let i = 0; i < institutionNames.length; i++) {
educations.push({
institutionName: institutionNames[i],
courseName: courseNames[i],
...
});
}
This is also a way to populate your desired format data.
$(document).ready(function(){
$(":button").click(function(){
var educations=$("#formCV .education");
var data=[];
educations.each(function(i,education){
var set={}
$(education).find(":input").each(function(i,value){
set[$(value).attr("name")] = $(value).val();
});
data.push(set);
})
console.log("data",data)
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form id="formCV" action="">
<div id="educationContainer">
<!-- First Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
<!-- Second Group -->
<div class="education">
<div>
<input type="text" name="institutionName">
</div>
<div>
<input type="text" name="courseName">
</div>
<div>
<input type="month" name="startDate">
</div>
<div>
<input type="month" name="endDate">
</div>
</div>
</div>
<input type="button" value="click me"/>
</form>
</body>
</html>

Toggle sub-category divs based on radio button selection

I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<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';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</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/>
Co-Op Category:<br />
<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" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<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() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</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/>
Co-Op Category:<br />
<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" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>

Categories

Resources