Display Placeholder text separately for each input - javascript

I have following code:
<div>
<input data-maxsale="9" data-maxsaleid="27595" name="cart[3839][qty]" value="1" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27595">
<p>
placeholder
</p>
</div>
</div>
<div>
<input data-maxsale="3" data-maxsaleid="27757" name="cart[3841][qty]" value="1" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27757">
<p>
placeholder
</p>
</div>
</div>
var maxSalInput = $('input[data-maxsaleid]');
$('.maxsalenotifcation').hide();
maxSaleInputs.each(function() {
var maxSaleID = $(this).attr('data-maxsaleid');
var maxSaleValue = $(this).val();
var maxSaleQuantity = $(this).attr('data-maxsale');
if (maxSaleValue > maxSaleQuantity) {
$('.maxsalenotifcation .maxsaleid-' + maxSaleID).show();
}
});
http://jsfiddle.net/bmpqo69g/
I want to display the placeholder separately for each maxsaleid when the input value is bigger than the maxSaleValue.
I can modify the html markup if needed.
How can i do this?

This maxSaleInputsvariable has not been defined.
You should define multiple classes like this $('.maxsalenotifcation.maxsaleid-' + maxSaleID) (without space in between classes)
Code Snippets:
$(function() {
var maxSalInput = $('input[data-maxsaleid]');
$('.maxsalenotifcation').hide();
maxSalInput.each(function() {
var maxSaleID = $(this).attr('data-maxsaleid');
var maxSaleValue = parseInt($(this).val());
var maxSaleQuantity = parseInt($(this).attr('data-maxsale'));
if (maxSaleValue > maxSaleQuantity) {
$('.maxsalenotifcation.maxsaleid-' + maxSaleID).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
<input data-maxsale="9" data-maxsaleid="27595" name="cart[3839][qty]" value="10" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27595">
<p>
placeholder
</p>
</div>
</div>
<div>
<input data-maxsale="3" data-maxsaleid="27757" name="cart[3841][qty]" value="4" title="Qty" class="input-text qty" maxlength="12">
<div class="maxsalenotifcation maxsaleid-27757">
<p>
placeholder
</p>
</div>
</div>

Related

Adding elements dynamically

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>

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>

change labels value with javascript, when no id or class

Can you help me for changing value with javascript, but code no have id or class here is code:
<label for="flights-origin-prepop-whitelabel_en">Origin</label>
I want change "Origin" with different word.
Some examples of my code:
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
How can change this placeholder "Destination", and label text Destination?
Thanks
You can change the origin texto doing this:
document.querySelector("label[for='flights-origin-prepop-whitelabel_en']").textContent = 'New Text';
Yes, sure, you can use querySelector with label selector including for data
console.log(document.querySelector("label[for='flights-destination-prepop-whitelabel_en']"))
<button role="flights_submit" type="submit">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
You can find the correct element using an "attribute selector" that looks for the for attribute and a specific value for it.
var btn = document.querySelector("button");
btn.addEventListener("click", function(){
var el = document.querySelector("[for=flights-destination-prepop-whitelabel_en]");
el.textContent = "New Value";
var input = document.getElementById("flights-destination-prepop-whitelabel_en");
input.setAttribute("placeholder","New Value");
});
<button role="flights_submit" type="button">Search</button>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text"
name="destination_name"
autocomplete="off" required=""
id="flights-destination-prepop-whitelabel_en"
placeholder="Destination"
data-label="Destination"
role="flights-destination"
data-modal-modifier="whitelabel_en"
data-placeholder-initialized="true">
<input type="hidden"
name="destination_iata"
id="flights-destination-whitelabel_en" value="">
</div>
The first step would be to set an array of the elements you want to target, which in this case is label. Then you would iterate through that array using a for loop to see if the textContent of that label is what you wanted to change. Finally, once you've 'hooked' the label you need, you can change the attributes for it as necessary. Please also note that textContent method is not cross browser compliant and so I've included a ternary script that will circumvent that thanks to this handy StackOverflow post .
HTML:
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>
JavaScript:
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
jsfiddle Example
//https://stackoverflow.com/a/285608/5076162
//https://stackoverflow.com/a/13506703/5076162
var labelArray = document.getElementsByTagName('LABEL');
console.log(labelArray);
var textToChange = 'Destination';
for (var i = 0; i < labelArray.length; i++) {
var currentLabel = labelArray[i]
var text = ('innerText' in labelArray[i]) ? 'innerText' : 'textContent';
if (currentLabel[text] === 'Destination') {
var matchingInput = document.getElementById(currentLabel.htmlFor);
var newText = 'changedDestination';
var newPlaceHolder = 'changedPlaceHolder';
currentLabel[text] = newText;
matchingInput.placeholder = newPlaceHolder;
}
}
<button role="flights_submit" type="submit">Search</button>
<br/>
<br/>
<div class="mewtwo-flights-destination">
<label for="flights-destination-prepop-whitelabel_en">Destination</label>
<input type="text" name="destination_name" autocomplete="off" required="" id="flights-destination-prepop-whitelabel_en" placeholder="Destination" data-label="Destination" role="flights-destination" data-modal-modifier="whitelabel_en" data-placeholder-initialized="true">
<br/>
<br/>
<label for="somethingElse">OtherLabel</label>
<input type="text" id='somethingElse'>
<input type="hidden" name="destination_iata" id="somethingElse" value="">
</div>

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>

getElementsByClassName and innerHTML

Can someone explain how to appendChild to a parent <div class="...">
and solve this ?
The innerHTML should set the variable str after every <div class='categories'> </div>
it created dynamically when you set a value to the texts and press the button "press"
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories');
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + "" + fieldValue + "" + categoryPart3;
for (var i = 0; i < newCategoryNode.length; i++) {
newCategoryNode[i].innerHTML=str;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" onchange="checkAll('divID',true,elem)" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onclick="addField()" value="Press">
</body>
<script>
function addField() {
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategory = document.getElementsByClassName('categories');
var div = document.createElement('div');
div.setAttribute('class', 'categories');
var a = document.createElement('a');
a.setAttribute('class', 'titles');
var hr = document.createElement('hr');
var input_check = document.createElement('input');
input_check.setAttribute('type', 'checkbox');
input_check.setAttribute('class', 'check');
var input = document.createElement('input');
input.setAttribute('type', 'text');
var br = document.createElement('br');
var textnode = document.createTextNode(fieldValue);
div.appendChild(input);
div.appendChild(a);
div.appendChild(hr);
div.appendChild(input_check);
div.appendChild(textnode);
div.appendChild(input);
div.appendChild(br);
div.appendChild(br);
console.log(div);
var node = document.getElementsByClassName('categories');
for (var i = 0; i < node.length; i++) {
node[i].appendChild(div);
}
}
</script>
</html>
hope this could give you idea on how to do it.
you cannot use appendChild to a node using a string it shoud also be a DOM element
you can check on document.createElement and document.createTextNode function
hope it would help you more on your understanding
According to MDN, Node.appendChild() wants a Node object as its argument. It won't create one from a string of markup, so you'll have to create it yourself.
You can use document.createElement() to create a Node object, then you can set its innerHTML as you like. Once the Node is all set how you want, you can add it to the DOM using appendChild().
If you want to use appendChild() mehtod it doesn't work this way.First you have to create a child using element.createElement() method.Now concentrating on your code i encountered some problem. your getElementsByClassName is returning a nodelist containing all the elements having same class.So if you want to grab it provide it an index.As you have only one it's better to provide [0] index to it.
var newCategoryNode = document.getElementsByClassName('categories')[0];
if you don't provide index in getElementsByClassName() you can also access it
newCategoryNode[0].innerHTMM=str
i removed for loop from you code.If you want to use loop use for...in loop instead as it is a list of object.
var newCategoryNode = document.getElementsByClassName('categories');
for(key in newCategoryNode){
newCategoryNode[key].innerHTML=str;
}
you haven't defined checkAll() function related to one of your input tag.That surely get you an error.I've modified your code and it might give you the result you want
function addField() {
console.log('logged');
var categoryValue = document.getElementById("newCateg").value;
var fieldValue = document.getElementById("newField").value;
// var selOption = document.option[selectedIndex.text];
var newCategoryNode = document.getElementsByClassName('categories')[0];
var categoryPart1 = [
' <div class="categories">',
'<input type="checkbox" class="check"/> <a class="titles">'].join('');
console.log(categoryPart1);
var categoryPart2 = [
'</a>',
' <hr/>',
' <input type="checkbox" class="check"/> ' ].join('');
var categoryPart3 = [
' <input type="text" />',
' <br> </br>',
'<hr/>',
'</div>'].join('');
var str=categoryPart1 + categoryValue + categoryPart2 + fieldValue + "" + categoryPart3;
console.log(str);
newCategoryNode.innerHTML =str;
}
<input type="text" id="newCateg" />
<input type="text" id="newField" />
<div class="categories">
<p class="titles">
<input type="checkbox" class="check" />FUN</p>
<hr/>
<div class="field">
<input type="checkbox" class="check" />D
<input type="text" />
</br>
</div>
<input type="checkbox" class="check" />
<label>S</label>
<input type="text" id="c1" />
</br>
<input type="checkbox" class="check" />
<label>A</label>
<input type="text" />
<hr/>
</div>
<input type="button" onClick="addField();" value="Press">

Categories

Resources