How to remove checkboxes in the form - javascript

function newCheckbox(){
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num){
var elm = null;
try {
elm=document.createElement('<input type="checkbox" id="chk'+num+'">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.id='chk'+num;
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
for(var i = 0; i<texts.length-1; i++){
var chbox=Box[i];
txt = texts[i];
if(chbox.checked){
chbox.parentNode.removeChild(chbox);
txt.parentNode.removeChild(txt);
}
}
}
form{
color:blue;
font-weight:bold;
margin:100 0 0 50;
font-weight:bold;
margin-left:120;
padding:100;
}
label{
display:block;
}
input{
color:blue;
background-color:pink;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" name="form1">
<div>
<label>Checkbox text:<input type="text" id="text"></label>
<input type="button" onclick="newCheckbox();"value="add">
<input type="button" value="Delete" onclick = "delBoxes();"/>
</div>
</form>
</body>
</html>
I want to have a dynamic page that allows a user to add checkboxes to the page. Checkbox content is the input in the textbox.
When the user pushes the “add”-button checkboxes are created and shown. The user must have the ability to remove checkboxes by marking them. The code can add a new checkbox to the form but the deleting function does not work.
It seems that chbox is not created and the if-statement does nothing in the function delBoxes.
Any suggestions?

Replace the whole script you have with this :
function newCheckbox() {
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num) {
var elm = null;
try {
elm=document.createElement('<input type="checkbox" class="chk">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.className='chk';
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
var chbox = document.form1.getElementsByClassName('chk');
for(var i = 0; i<texts.length-1; i++){
if(chbox[i].checked){
chbox[i].parentNode.removeChild(chbox[i]);
texts[i].parentNode.removeChild(texts[i]);
}
}
}

Related

How to pass Range Values into an HTML sidebar to be ticked or selected then save selections using GAS?

As the sidebar is open, it displays the colors (color name and its HEX #, which are sitting in a sheet) and displays also a checkbox next to each color.
The user ticks the checkbox or selects the colors how many he/she wants all the way down, clicks on save and the list gets saved into an array...maybe PropertiesService.getDocumentProperties()
Here's the code I got for the sidebar and getting the colors from the range:
var ss = SpreadsheetApp.getActiveSpreadsheet();
function showSideBar() {
var ui = SpreadsheetApp.getUi();
var tmp = HtmlService.createTemplateFromFile('pickColor');
var html = tmp.evaluate();
html.setTitle('Escolha as cores');
ui.showSidebar(html);
}
function getColors() {
const colorListSheet = ss.getSheetByName('CadCores');
const colorList = colorListSheet.getRange(2,1,colorListSheet.getLastRow(),2).getValues();
return colorList;
}
Here's the html part, whose body I can't make it dynamic being a newbie. Listed Yellow as an example, but I suppose that having the checkbox, the color name and its hex would require it to be a table, correct?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="Yello" type="checkbox">
<label for="yellow">Yellow</label>
<br>
<br>
<button id='salvar-cores'>Salvar Cores</button>
<br>
<br>
<script>
let colorArray = 10;//But this would be the getColors' length, right?
function addColor(colors){
for (let i = 0; i < colorArray; i++){
$(i + 1).text(colors[i]);
}
};
google.script.run.withSuccessHandler(addColor).getColors();
</script>
</body>
</html>
Any direction is appreciated.
You can always put a ballot symbol into a select option and toggle on or off. Here is an example.
Code.gs:
function onOpen() {
try {
var menu = SpreadsheetApp.getUi().createMenu("Cad Colors");
menu.addItem("Get Colors", "showGetColors");
menu.addToUi();
}
catch(err) {
Logger.log(err);
}
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function showGetColors() {
try {
var html = HtmlService.createTemplateFromFile("HTML_GetColors").evaluate();
SpreadsheetApp.getUi().showSidebar(html);
}
catch(err) {
SpreadsheetApp.getUi().alert(err);
}
}
function getColors() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("CadColors");
return sh.getDataRange().getValues();
}
catch(err) {
Logger.log(err);
}
}
function setColors(checked) {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName("CadColors");
sh.getRange(2,3,checked.length,1).setValues(checked);
}
catch(err) {
Logger.log(err);
}
}
Then if the HTML file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<select id="colorSelect" onchange="colorOnChange()" ondblclick="colorDblClick()"></select>
<input type="button" onclick="colorSaveClick()" value="Save Colors">
<?!= include("JS_GetColors"); ?>
</body>
</html>
I've seperated out the javascript in a seperate file that is included into a HTML Template:
<script>
function colorOnChange() {
try {
var select = document.getElementById("colorSelect");
var option = select.options[select.selectedIndex];
var text = option.text;
text = text.charAt(0) === "☐" ? "☑" : "☐";
text = text.concat(option.text.slice(1));
option.text = text;
}
catch(err) {
alert(err);
}
}
function colorDblClick() {
try {
var select = document.getElementById("colorSelect");
var text = select.value;
var option = null;
text = text.charAt(0) === "☐" ? "☑" : "☐";
text = text.concat(select.value.slice(1));
for( var i=0; i<select.options.length; i++ ) {
option = select.options[i];
if( option.text.slice(1) === text.slice(1) ) {
option.text = text;
break;
}
}
select.value = text;
}
catch(err) {
alert(err);
}
}
function colorSaveClick() {
try {
var select = document.getElementById("colorSelect");
var checked = [];
for( var i=0; i<select.options.length; i++ ) {
// note that checked is an array of arrays
checked.push( select.options[i].text.charAt(0) === "☑" ? [true] : [false] );
}
google.script.run.setColors(checked);
}
catch(err) {
alert(err);
}
}
(function () {
try {
google.script.run.withSuccessHandler(
function (colors) {
try {
var option = null;
var text = null;
// omit first line
for( var i=1; i<colors.length; i++ ) {
option = document.createElement("OPTION");
text = document.createTextNode("☐ "+colors[i][0]+" "+colors[i][1]);
option.appendChild(text);
document.getElementById("colorSelect").appendChild(option);
}
}
catch(err) {
alert(err);
}
}
).getColors();
}
catch(err) {
alert(err);
}
}());
</script>
The only difficulty is handling the select.value. To toggle it you have to double click. Every other one you can select and toggle from the drop down. The status of the selections is returned to the spreadsheet using setColors().
My spreadsheet looks like this:
And the sidebar like this:
I think this could work for you
1. I got all the colors in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
function showSideBar() {
var ui = SpreadsheetApp.getUi();
var tmp = HtmlService.createTemplateFromFile('pickColor');
var html = tmp.evaluate();
html.setTitle('Escolha as cores');
ui.showSidebar(html);
}
function getColors() {
const colorListSheet = ss.getSheetByName('CadCores');
const colorList = colorListSheet.getRange(2,1,colorListSheet.getLastRow() -1,2).getValues();
return colorList;
}
function onOpen(){
showSideBar()
}
2. Render the colors in the DOM
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id='color-name'></div>
<br>
<button id='salvar-cores'>Salvar Cores</button>
<script>
function afterLoad(){
google.script.run.withSuccessHandler(afterDataReturned).getColors();
}
function afterDataReturned(arrayOfArrays){
const item = document.getElementById("color-name")
arrayOfArrays.forEach(function(row){
let input = document.createElement("input")
input.type = "checkbox"
input.id = row[0]
input.value = row[1]
item.appendChild(input)
let label = document.createElement("label")
label.setAttribute('for',row[0])
label.textContent = row[0]
item.appendChild(label)
})
}
document.addEventListener("DOMContentLoaded", afterLoad)
</script>
</body>
</html>
3. Add any other color you want in the sheet and refresh the menu, so it reloads the new colors

How to create a JavaScript loop to display an output 100 times

I’m doing an exercise for high school. The exercise is to create an input and the input needs to be displayed 100 times ( 1) input 2) input 3) input, etc..) and you are not allowed to do it manually; you need to create a loop.
This is what I have so far. I tried googling it for an hour, but I didn't find anything.
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var str = something;
showReply("output", reply);
}
var something = [
[var text = "";]
[var i;]
[for (i = 0; i < 5; i++) {]
[reply += i + ")" + textFromUser;}]
]
</script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output"></span> </p>
</body>
</html>
How can I do it?
You can create an element and append to your output container using a for loop. Try this:
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
let container = document.getElementById(id);
let p = document.createElement('p');
p.textContent = reply;
container.appendChild(p);
}
function reply(){
var textFromUser = getText("myTextField");
for(let i = 0; i < 100; i++){
showReply("output", textFromUser);
}
}
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <div id="output"></div> </p>
Variable i is used as a counter. If you want to change how many times it loops, just change the i<=num.
for (var i=1; i<=100; i++){
show_reply();
}
I suggest you to check this post on W3Schools.
I've made two files, one for HTML and the other for JavaScript.
Here is the JavaScript code:
function getText(id) {
let text = document.getElementById(id).value;
return text;
}
function showReply(id, reply) {
document.getElementById(id).innerHTML = reply;
}
function reply() {
let textFromUser = getText("myTextField");
let i;
let span1 = document.getElementById("output")
let usert = ""
for (i = 0; i < 100; i++) {
usert += "<br>" + textFromUser
}
span1.innerHTML = usert
}
Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script src="main.js"></script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output">dd</span> </p>
</body>
</html>
There are many different potential solutions for this type of question. Choose the flavor you like and put your own spin on it.
function showReply(id, reply){
document.getElementById(id).innerHTML = reply.join('<br>');
}
function reply(){
var textFromUser = getText('myTextField');
var outputs = [];
for (let i = 0; i < 100; i++){
outputs.push(`#${ i } ${ textFromUser }`)
}
showReply('output', outputs);
}

How do I activate a function with a second <button> to call a forEach?

let words = [];
var longestCt = 0;
var longestWord = "";
var myList = [];
var myList = ['Loops','are','used','while','Learning JavaScript'];
function addWords() {
let template = words.map(word => `<li>${word}</li>`).join('\n');
document.querySelector('ul').innerHTML = template;
}
addWords();
let btnAdd = document.querySelector('button');
let input = document.querySelector('input');
btnAdd.addEventListener('click', () => {
words.push(input.value);
input.value = '';
addWords();
});
let findLong = document.querySelector('button');
findLong.addEventListener('click', () => {
let longestCt = 0;
let longestWord = "";
words.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value;
longestCt = value.length;
} else {
longestWord = longestWord;
}
});
//}
});
document.getElementById("demo2").innerHTML = longestWord;
div {
widows: 20%;
margin: auto;
}
input, button {
padding: 5px;
display: inline-block;
}
li {
font-size: 20px;
font-weight: bold;
margin-left: -40px;
list-style: none;
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test_Arr_Input.css">
<title>Test Longest Array.html</title>
</head>
<body>
<!--Thank you to YouTube KodeBase with my modifications adding a second button which isn't working-->
<div>
<input type="text">
<button>Add a Word</button>
<ul></ul>
<br>
<button>Find the Longest</button>
<p id="demo"></p>
</div>
<script type="text/javascript" src="test_Arr_Input.js"></script>
</body>
</html>
Full disclosure; Beginner. With that said; thank you in advance.
I have written a simple JavaScript to return the longest string in an array.
Here it is as simply a JavaScript function, that I ran from the console, without interacting with the html:
var myList = ['Loops','are','used','while','Learning JavaScript'];
var longestCt = 0;
var longestWord = "";
myList.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value; longestCt = value.length;
} else {
longestWord = longestWord;
}
});
console.log(longestWord);
I then endeavored to create an HTML page to enter objects into the array and to create a list.
(Thanks to KodeBase from Youtube for the direction). The JavaScript for this is posted at the end after the CSS. Here is the HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test_Arr_Input.css">
<title>Test Longest Array.html</title>
</head>
<body>
<!--Thank you to YouTube KodeBase with my modifications adding a second button which isn't working-->
<div>
<input type="text">
<button>Add a Word</button>
<ul></ul>
<br>
<button>Find the Longest</button>
<p id="demo"></p>
</div>
<button onclick="intoMyList()">Submit to the array</button>
<p id="demo"></p>
<button onclick="findTheLongest()">Find the Longest Word</button>
<p id="demo2"></p>
<script type="text/javascript" src="test_Arr_Input.js"></script>
</body>
</html>
Here is the CSS:
div {
widows: 20%;
margin: auto;
}
input, button {
padding: 5px;
display: inline-block;
}
li {
font-size: 20px;
font-weight: bold;
margin-left: -40px;
list-style: none;
}
And here is the final JavaScript:
let words = [];
function addWords() {
let template = words.map(word => `<li>${word}</li>`).join('\n');
document.querySelector('ul').innerHTML = template;
}
addWords();
let btnAdd = document.querySelector('button');
let input = document.querySelector('input');
btnAdd.addEventListener('click', () => {
words.push(input.value);
input.value = '';
addWords();
});
let findLong = document.querySelector('button');
findLong.addEventListener('click', () => {
//function findTheLongest() {
let longestCt = 0;
let longestWord = "";
myList.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value;
longestCt = value.length;
} else {
longestWord = longestWord;
}
});
//}
});
document.getElementById("demo2").innerHTML = longestWord;
First I changed a few variable names for more clarity.
But the issue is, although I am able to get the words to enter the array by clicking the first button, the second button does not seem to call the ForEach function to trigger the return of the longest word. I am wondering if I need to somehow differentiate between button 1 and 2 in the HTML. Or if I just need to go back to the drawing board to rethink my understanding of the way I am putting the JS together.
In short, you need to give each of your buttons a unique ID and then you can use this Id to target the appropriate button in your code.
<button id="add-word">Add a Word</button>
and
let btnAdd = document.querySelector('#add-word');
As mentioned by Jamiec you should give each button its own unique id and use getElementById to target it specifically with that or you can use onclick="function()" in the html to call a function from that element directly
The current point of failure also seems to be line 27 reads myList.forEach when it should be words.ForEach. I've changed a few lines and got a working example here for you: https://jsfiddle.net/z7dsabLc/6/

Trying to print out a input text the number of times the user wrote in the secound input using a while loop

I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}

Javascript: How to remove element binded to remove button (dynamic)

I am currently using an add button to add input from a text box into a list. I am also binding a button to each of these list elements and then appending them to the unordered list. How do I remove the element onclick of the corresponding remove button? Pure JavaScript only.
window.onload = function() {
var elements = [];
var textInput;
document.getElementById("addButton").onclick = function() {
textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
}
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<!DOCTYPE html>
<html>
<body>
<head>
<script src="func.js"></script>
</head>
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>
</body>
</html>
Use addEventListener to register click event over created button.
Use .remove(), removes the object from the tree it belongs to.
Try this:
window.onload = function() {
var elements = [];
document.getElementById("addButton").onclick = function() {
var textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
btnNode.addEventListener('click', removeHandler);
}
}
function removeHandler() {
this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>

Categories