Dynamic checkbox list in javascript - not working - javascript

I'm trying to create a list of checkboxes when a certain element is selected from the dropdown list. However, in the following code I am getting only the last element in the checkbox list. That is, at the output, there aren't 3 checkboxes (length of my array) but there is only one - only with the last element in the array.
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function chooseTable(db) {
if(db=="hr.employee"){
var div = document.getElementById("table");
var ids = ["id","name", "write_uid"];
var main = document.getElementById('main1');
var parentElement = document.getElementById('ids');
for(var count in ids)
{
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
parentElement.innerHTML = ids[count];
newCheckBox.value = ids[count];
parentElement.appendChild(newCheckBox);
}
}
}
</script>
<center>
<bold>
<h2>
Make Query
</h2>
</bold>
<div id="main1">
<div>
Choose database:<br/>
<select id="table" name="table" onchange="chooseTable(this.value)">
<option name="choice" value=""></option>
<option name="choice1" value="hr.employee">Employees</option>
<option name="choice2" value="account.account">Accounts</option>
</select>
</div>
<div id="ids">
</div>
</div>
</center>
</body>
</html>

the problem is the parentElement.innerHTML = ids[count]; code. It clean all the previous html content. And to add label to the checkbox it's better use label tag. Try this:
for(var count in ids)
{
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
newCheckBox.value = ids[count];
parentElement.appendChild(newCheckBox);
var newLabel = document.createElement('label');
newLabel.innerHTML = ids[count];
parentElement.appendChild(newLabel);
}

because innerHTML method will clean its own inside and rewrite new element.
how about try this?
for(var count in ids)
{
var newCheckBox = document.createElement('input');
var newSpan = document.createElement('span');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
newSpan.innerHTML = ids[count];
newCheckBox.value = ids[count];
parentElement.appendChild(newSpan);
parentElement.appendChild(newCheckBox);
}

Related

Dynamically created Select Options behave differently when called from a button vs directly in function Materialize CSS

document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
const container = document.getElementById("stringcontainer");
var select = createSelect(1);
select.addEventListener('change', hello);
container.appendChild(select);
function add(){
var select1 = createSelect(2);
select1.addEventListener('change', hello);
container.appendChild(select1);
}
function createSelect(num){
//Create array of options to be added
var array = ["Option 1","Option 2","Option 3"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "asp"+num;
//selectList.className = "browser-default";
selectList.required = true;
selectList.innerHTML += "<option disabled selected>Choose Option</option>"
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].split(" ").join("").toLowerCase();
option.text = array[i];
selectList.appendChild(option);
}
return selectList;
}
function hello(){
console.log("Added EventListener");
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/css/materialize.min.css">
<div class="row">
<div id="stringcontainer"/>
</div><!-- CLOSE ROW -->
<div class="row">
<div class="input-field col s3">
<button id="astring" class="waves-effect waves-light btn-small"
onclick="add()">Add</button>
</div>
</div><!-- CLOSE ROW -->
<script src="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/js/materialize.min.js"></script>
Called from JS as a function:
Called from a button with the same function:
The result is an invisible unstyled select when you press the button.
I'm using Materialize CSS. The eventListener is also not working properly when adding from the button also. It works for a console log but anything more complex like getSelectedValues(), it fails
I expected the Select to render the same way as the first image. Can anyone explain why this happening and offer a solution?
The problem is, you apply the css only once in the beginning by using
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
You have to do the same, each time you add a new select. So, the following should work the way you want it to.
document.addEventListener('DOMContentLoaded', function() {
applyCSS();
});
const container = document.getElementById("stringcontainer");
var select = createSelect(1);
select.addEventListener('change', hello);
container.appendChild(select);
function add(){
var select1 = createSelect(2);
select1.addEventListener('change', hello);
container.appendChild(select1);
applyCSS();
}
function createSelect(num){
//Create array of options to be added
var array = ["Option 1","Option 2","Option 3"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "asp"+num;
//selectList.className = "browser-default";
selectList.required = true;
selectList.innerHTML += "<option disabled selected>Choose Option</option>"
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].split(" ").join("").toLowerCase();
option.text = array[i];
selectList.appendChild(option);
}
return selectList;
}
function hello(){
console.log("Added EventListener");
}
function applyCSS(){
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/css/materialize.min.css">
<div class="row">
<div id="stringcontainer"/>
</div><!-- CLOSE ROW -->
<div class="row">
<div class="input-field col s3">
<button id="astring" class="waves-effect waves-light btn-small"
onclick="add()">Add</button>
</div>
</div><!-- CLOSE ROW -->
<script src="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/js/materialize.min.js"></script>
I moved the code, which applies the CSS into applyCSS and then call it once in the DOMContentLoaded event listener and also each time the add function is called.

Display selected checkbox values in an HTML using javascript/ google script

I created a Select Element which creates Checkbox dropdown elements based on the items on the Google sheet.
Here is my HTML code:
<div class="form-row">
<div class="multiselect form-group">
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control" >
<option>Select an option</option>
</select>
<div class="overSelect" ></div>
</div>
<div id="checkboxes">
</div>
</div>
Here is my javascript code:
<script>
document.addEventListener("DOMContentLoaded", afterLoad);
document.getElementById("checkboxes").addEventListener("change", loadDisplayPos);
function afterLoad(){
google.script.run.withSuccessHandler(loadPosApp).checkPosApp();
}
function loadPosApp(postOpen){
postOpen.forEach(function(r){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = r[0];
var label = document.createElement('label')
label.appendChild(checkbox);
label.appendChild(document.createTextNode(" " + r[0]));
var content = document.getElementById('checkboxes');
content .appendChild(label);
});
}
function loadDisplayPos(){
var contentCheck = document.getElementById('checkboxes').value;
console.log(contentCheck);
}
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
Here is my Google Apps Script function:
function checkPosApp()
{
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("VacantPositions_Data");
//const myDates = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
var postOpen = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
Logger.log(postOpen)
return postOpen;
}
Upon the load of the Web App, it will load the values from the Google sheet to the Web App as dropdown checkboxes. My problem is how to display the checked items to the Select Element as selected. I tried to get the value of the element ID "checkboxes" but it says undefined. Do you have any suggestions or advice? I am still trying to look for a solution. Thank you in advance for the help.
I got the idea on how to answer my problem in this link: https://www.dyn-web.com/tutorials/forms/checkbox/group.php. I just modified it in a way that I could get all the checked/ selected in an array then display it in the Web App
Here is the modified function in javascript.
function loadDisplayPos(){
var element = document.getElementById('checkboxes');
var tops = element.getElementsByTagName('input');
var tags = [];
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
if (tops[i].checked){
tags.push( tops[i].value);
}
}
}
var selectedPost = document.getElementById('posapp').innerHTML= tags;
}

Appending new DOM elements to existing elements

I am trying dynamically increase the number of selects my form has on a website. I use javascript to do so.
JS code:
var div = document.getElementById("graph-form");
var para = document.createElement('span');
para.innerHTML = "Test Type";
var form = document.getElementById("form-id");
var selectList = document.createElement("select");
selectList.setAttribute("name","Test");
for(var i = 0; i < test_form_values.length; i++){
var option = document.createElement("option");
option.value = test_form_values[i];
option.text = test_form_text[i];
selectList.appendChild(option);
}
form.appendChild(para);
form.appendChild(selectList);
var para = document.createElement('span');
para.innerHTML = "Parameter";
var selectList = document.createElement("select");
selectList.setAttribute("name","Parameter");
for(var i = 0; i < param_form_values.length; i++){
var option = document.createElement("option");
option.value = param_form_values[i];
option.text = param_form_text[i];
selectList.appendChild(option);
}
form.appendChild(para);
form.appendChild(selectList);
Html code:
<form action="/analytics" method = "post"></form>
<div id = "form-id">
<span>Test Type </span>
<select name="Test">
<option value="Aop2DContact">AOP 2D Contact</option>
<option value="Aop2DMag">AOP 2D Magnification</option>
</select>
<span>Parameter </span>
<select name="Parameter">
<option value="MTF1">MTF at 2 lp/mm parallel</option>
<option value="MTF2">MTF at 4 lp/mm parallel</option>
</select>
</div>
<div class="buttons">
<input type="submit">
</div>
</form>
After appending:
After I append the newly created elements, it not only doesn't append inside the element but takes the div I had placed inside the element and moved it outside. I feel like there is probably an obvious answer as to why my HTML is getting restructured but I am not sure what that is.
Like Turnip commented, you are ending your form right after you open it.
Also, your JS is looking to append to the element with the id "form-id" and your form does not have that id, your inner div does.

How to get the name or id of a select dropdown in a dynamic form

I have a dynamic form with a select dropdown, and I want to know what select was changed, however any time that I add a new form and try to change any select the alert is the same: "origen1"
Here is my js code:
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var etiquetas = new Array();
var origenes = new Array();
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a label dynamically
var etiqueta = document.createElement("input");
etiqueta.setAttribute("name", 'etiqueta' + count);
etiqueta.setAttribute("value", "etiqueta");
etiqueta.setAttribute('disabled', true);
etiquetas.push(etiqueta);
//create a select dynamically
var myarray=new Array(3)
myarray[0] = "Opt1"
myarray[1] = "Opt2"
myarray[2] = "Opt3"
var origen = document.createElement("select");
origen.setAttribute("name", 'origen' + count);
for (i=0; i<3; i++)
{
opt = document.createElement('option');
opt.value = i;
opt.innerHTML = myarray[i];
origen.appendChild(opt);
}
origen.onchange = function(){testselect(this);};
origenes.push(origen);
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(etiqueta);
eleDiv.appendChild(origen);
eleDiv.appendChild(eleBtn);
}
function testselect(seleccion)
{
alert(seleccion.name);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
And the html:
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px">
</div>
<input type="submit" value="Submit"/>
</form>
Try inspecting the drop down using firebug. With that you might be able to get the name and ID of the selected drop down but remember the selected drop down has to be selected using firebug in order to see the ID or name used with it.
Since this is JS and the drop down is not selected properly you might not see the name or id used.
So make sure to it is properly selected

HTML and JS : Capture Key Value pairs in HTML form

I have a Spring MVC application where I am required to capture a variable number of key value pairs based on user input. The HTML & JS part of the code to render the controls is as follows :
<tr>
<td><label>Attributes (Names & Value(s))</label></td>
<td><input id="Button1" type="button" value="Add" onclick="Button1_onclick()"/></td>
</tr>
<script language="javascript" type="text/javascript">
var NumOfRow = 1;
var attribs = {};
function Button1_onclick() {
NumOfRow++;
// get the reference of the main Div
var mainDiv = document.getElementById('MainDiv');
// create new div that will work as a container
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'innerDiv' + NumOfRow);
//create span to contain the text
var newSpan = document.createElement('span');
newSpan.innerHTML = "Attribute Type";
// create new textbox for type entry
var newTextBox = document.createElement('input');
newTextBox.type = 'text';
newTextBox.setAttribute('id', 'DimensionType' + NumOfRow);
//create span to contain the text
var newSpan2 = document.createElement('span');
newSpan2.innerHTML = "Attribute Value(s)";
// create new textbox for value entry
var newTextBox2 = document.createElement('input');
newTextBox2.type = 'text';
newTextBox2.setAttribute('id', 'DimensionValue' + NumOfRow);
// create remove button for each attribute
var newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = 'Remove';
newButton.id = 'btn' + NumOfRow;
// attach event for remove button click
newButton.onclick = function RemoveEntry() {
var mainDiv = document.getElementById('MainDiv');
mainDiv.removeChild(this.parentNode);
NumOfRow--;
}
// append the span, textbox and the button
newDiv.appendChild(newSpan);
newDiv.appendChild(newTextBox);
newDiv.appendChild(newSpan2);
newDiv.appendChild(newTextBox2);
newDiv.appendChild(newButton);
// finally append the new div to the main div
mainDiv.appendChild(newDiv);
}
}
</script>
I am not sure how to send this captured data back to my controller when the form is submitted. Please advise. Also if there is a better way to capture such data, those suggestions are most welcome as well.
What about making Capture key event in a text field you can do this :
<html>
<head>
<script language="JavaScript" type = "text/javascript">
<!--
document.onkeypress = DisplayMsg;
function DisplayMsg(key_event)
{
if (document.all) //Checks for IE 4.0 or later
{
document.form1.text2.value = String.fromCharCode(event.keyCode);
}
else if (document.getElementById) //checks for Netscape 6 or later
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
else if (document.layers) //Checks for Netscape 4
{
document.form1.text2.value = String.fromCharCode(key_event.which);
}
}
//-->
</script>
<title>Capture Key Pressed</title>
</head>
<body>
<form name="form1">
<b>Type value in field: See what you typed:</b><br>
<input type = "text" name = "text1" onKeyPress="DisplayMsg(event)" size="20">
<input type = "text" name = "text2" onKeyPress="DisplayMsg(event)" size="20">
</form>
</body>
</html>

Categories

Resources