Creating check-boxes out of an array in JavaScript - javascript

I have an array, which is hard-coded for now, and I am trying to create checkboxes based on the array elements that I have.
var features = document.getElementById('features')
var options = ["Col1", "Col2", "Col3", "Col4", "Col5"];
for(var i = 0; i < options.length; i++) {
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.innerHTML = options[i];
x.name = options[i];
features.appendChild(x);
}
<label>Select Target</label>
<select name="targetColumn" id="selectTargetOptions">
<option value="selectcard">Select Target</option>
</select>
<br><br>
<label>All Features:</label>
<div id='features'>
</div>
<br>
<button id="btn-features">Select All</button>
<br><br>
<button id="btn-remove">Remove All</button>
I cannot see names of checkboxes as the elements of the array.
Any help please?

Checkboxes do not automatically add a label next to them. So you need to add the <label> tag for each checkbox. In my version of your code here, I have also added the for attribute to each label so that clicking the label will toggle it's matching checkbox.
var features = document.getElementById('features')
var options = ["Col1", "Col2", "Col3", "Col4", "Col5"];
for(var i = 0; i < options.length; i++) {
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.value = options[i];
x.id = 'checkbox-' + options[i];
var y = document.createElement('LABEL');
y.textContent = options[i];
y.setAttribute('for', x.id);
features.appendChild(x);
features.appendChild(y);
}
<label>Select Target</label>
<select name="targetColumn" id="selectTargetOptions">
<option value="selectcard">Select Target</option>
</select>
<br><br>
<label>All Features:</label>
<div id='features'>
</div>
<br>
<button id="btn-features">Select All</button>
<br><br>
<button id="btn-remove">Remove All</button>
As suggested by Scott Marcus, you may also choose to wrap your label around the checkbox to avoid the need to use the for attribute and an id. Here is one way to do it:
var features = document.getElementById('features')
var options = ["Col1", "Col2", "Col3", "Col4", "Col5"];
for(var i = 0; i < options.length; i++) {
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.value = options[i];
var z = document.createElement('SPAN');
z.textContent = options[i];
var y = document.createElement('LABEL');
y.appendChild(x);
y.appendChild(z);
features.appendChild(y);
}
<label>Select Target</label>
<select name="targetColumn" id="selectTargetOptions">
<option value="selectcard">Select Target</option>
</select>
<br><br>
<label>All Features:</label>
<div id='features'>
</div>
<br>
<button id="btn-features">Select All</button>
<br><br>
<button id="btn-remove">Remove All</button>

Well, if you have the balls to use .innerHTML (at least once), you could simply do it like this: ;-)
var options = ["Col1", "Col2", "Col3", "Col4", "Col5"];
document.getElementById('features').innerHTML=
options.map(o=>'<label><input type="checkbox" name="'+o+'">'+o+'</label>').join(" ");
document.onclick=ev=>{
if (ev.target.tagName==="BUTTON")
document.querySelectorAll("input[type=checkbox]").forEach(c=>c.checked=ev.target.textContent[0]==="S")}
<label>Select Target</label>
<select name="targetColumn" id="selectTargetOptions">
<option value="selectcard">Select Target</option>
</select>
<br><br>
<label>All Features:</label>
<div id='features'>
</div>
<br>
<button id="btn-features">Select All</button>
<br><br>
<button id="btn-remove">Remove All</button>

Related

data transfer multiple var

I'm making a website that sells keyboards stuff and I want to transfer and display multiple options selected by a user in a text field separated with commas(,) I tried using document.getElementById("product", "product2") but it does not work.
Here's what I have for now.
<div class="input-name">
<label for="products">Cases: </label>
<select name="product" id="product" class="larger" onchange="change()">
<option selected>--Please select--</option>
<script>productlist1()</script>
</select>
</div>
<div class="input-name">
<label for="products">Keycaps: </label>
<select name="product" id="product2" class="larger" onchange="change()">
<option selected>--Please select--</option>
<script>productlist2()</script>
</select>
</div>
<div class="input-name">
<label for="subject" id="subjectLabel">RE: Enquiry on</label>
<input type="text" name="subject" id="subject" class="subject_1" readonly>
</div>
function storeSub() {
document.getElementById("product").selectedIndex = sessionStorage.productIndex;
var product = document.getElementById("product").value;
sessionStorage.subject = product;
document.getElementById("subject").value = sessionStorage.subject;
}
function productlist1() {
var select = document.getElementById("product");
var options = ["Case1", "Case2", "Case3", "Case4"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function productlist2() {
var select = document.getElementById("product2");
var options = ["Keycaps1", "Keycaps2", "Keycaps3", "Keycaps4"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function change() {
var product = document.getElementById("product").value;
sessionStorage.product = product;
document.getElementById("subject").value = sessionStorage.product;
}
You can attach a change event listener changeSelection to both select elements. So once anything is selected or a selection is changed, the listener will be invoked and the event is automatically passed as an argument.
Now Inside changeSelection listener, you can get the selected option by event.target.value.
You can use a Set to uniquely keep track of the selections. To retrieve the selections as a comma-separated string, you just need to convert the Set to an array and join it with comma.
document.addEventListener("DOMContentLoaded", function(){
let select1 = document.getElementById("product");
let options1 = ["Case1", "Case2", "Case3", "Case4"];
options1.forEach(option => {
let el = document.createElement("option");
el.textContent = option;
el.value = option;
select1.appendChild(el);
})
select1.addEventListener('change', changeSelection)
let select2 = document.getElementById("product2");
let options2 = ["Keycaps1", "Keycaps2", "Keycaps3", "Keycaps4"];
options2.forEach(option => {
let el = document.createElement("option");
el.textContent = option;
el.value = option;
select2.appendChild(el);
})
select2.addEventListener('change', changeSelection)
});
const selections = new Set();
function changeSelection(event){
selections.add(event.target.value)
let subjectInput = document.getElementById("subject");
subjectInput.value = Array.from(selections).join(',');
}
<div class="input-name">
<label for="products">Cases: </label>
<select name="product" id="product" class="larger">
<option selected>--Please select--</option>
</select>
</div>
<div class="input-name">
<label for="products">Keycaps: </label>
<select name="product" id="product2" class="larger">
<option selected>--Please select--</option>
</select>
</div>
<div class="input-name">
<label for="subject" id="subjectLabel">RE: Enquiry on</label>
<input type="text" name="subject" id="subject" class="subject_1" readonly>
</div>

Why select field not displaying?

I'm trying to add select field by both ways first is dynamically and giving values to select fields.
while trying with dynamically so it is working well. but when trying to display some select field by
giving value to '1st room child' select field so first time im receiving the output but second time its
doesn't worked
$(function () {
/*here my values to increment whenever added newly form */
var i = 1;
i++;
var max_fields = 6;
var this_button_work_for_click_to_add_rooms = $(".this_button_work_for_click_to_add_rooms");
var this_is_field_wrapper = $(".this_is_field_wrapper");
//here we starting counting...
var input_count = 1;
//add buttong dynamically over here...
$(this_button_work_for_click_to_add_rooms).click(function (event) {
/* Act on the event */
if (input_count < max_fields) {
input_count++;
var add_fields = '<div><div class="row"><div class="form-group"><div class="col-xs-1"><h6>Options -</h6><h6 class="#">Adults(12+)</h6><select id="selected_adults[]" name="selected_adults[]" class="form-control"><option value="1">1</option><option selected="selected" value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select></div><!-- </div><div class="form-group"> --><div class="col-xs-1"><h6>' + input_count + ' Room</h6><h6 class="m_label">Child(0-12)</h6><select id="selected_childs[]" name="selected_childs[]" onchange="displayingNumberOfChildAge(this);" class="form-control"><option>select</option><option id="first_child_col" value="1">1</option><option id="second_child_col" value="2">2</option></select></div><!-- </div><div class="form-group"> --><div id="childage0" class="col-xs-1"><h6></h6></div><div id="childage1" class="col-xs-1"><h6></h6></div>remove</div><!-- here ending form group --></div><!-- here ending row --></div>';
$(this_is_field_wrapper).append(add_fields);
}
});
$(this_is_field_wrapper).on('click', '.remove_input_button', function (e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
function addFields() {
var number = document.getElementById("selected_childs[]").value;
var childage = document.getElementById("childage0");
//Create array of options to be added
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
while (childage.hasChildNodes()) {
childage.removeChild(childage.lastChild);
}
if (number == 1) {
// statement
for (i = 0; i < number; i++) {
var h = document.createElement("h6");
h.setAttribute("id", "firstever");
var h1 = document.createElement("h6");
h1.appendChild(document.createTextNode("select child age"));
childage.appendChild(h1);
h.appendChild(document.createTextNode("Children Age " + (i + 1)));
childage.appendChild(h);
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
selectList.setAttribute("class", "form-control");
childage.appendChild(selectList);
childage.appendChild(document.createElement("br"));
//Create and append the options
for (var j = 0; j < array.length; j++) {
var option = document.createElement("option");
option.setAttribute("value", array[j]);
option.text = array[j];
selectList.appendChild(option);
}
}
} else {
// statement
for (i = 0; i < number; i++) {
childage = document.getElementById("childage" + i);
var h1 = document.createElement("h6");
h1.setAttribute("id", "secondever");
h1.appendChild(document.createTextNode("select child age"));
childage.appendChild(h1);
var h = document.createElement("h6");
h.appendChild(document.createTextNode("Children Age " + (i + 1)));
childage.appendChild(h);
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");
selectList.setAttribute("class", "form-control");
childage.appendChild(selectList);
childage.appendChild(document.createElement("br"));
//Create and append the options
for (var j = 0; j < array.length; j++) {
var option = document.createElement("option");
option.setAttribute("value", array[j]);
option.text = array[j];
selectList.appendChild(option);
}
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Welcome|Home</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="<?php echo base_url(); ?>index.php/dynamically_added_controller/Dynamically/addingValues">
<div class="this_is_field_wrapper">
<div class="row">
<div class="form-group">
<div class="col-xs-1">
<h6>Options -</h6>
<h6 class="#">Adults(12+)</h6>
<select id="selected_adults[]" name="selected_adults[]" class="form-control">
<option value="1">1</option>
<option selected="selected" value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="col-xs-1">
<h6>1st Room</h6>
<h6 class="m_label">Child(0-12)</h6>
<select id="selected_childs[]" name="selected_childs[]" value="" onchange="addFields()" class="form-control">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="childage0" class="col-xs-1">
<h6></h6>
</div>
<div id="childage1" class="col-xs-1">
<h6></h6>
</div>
<div class="col-xs-1">
Click & Add Rooms
</div>
</div>
</div>
</div>
<button type="submit" value="submit">click to submit</button>
</form>
</body>
</html>
As you have seen the problem is while attempting second time to display select field by giving value to '1st room child' select field so it is not working.
Your problem is something called "delegation." When you dynamically add something to the DOM that wasn't there when it was first loaded, you have to look through a pre-existing parent first.
Consider this. You have an existing element: <div id="loaded"></div>
Then, you dynamically add something in that div: <button type="button" id="someButton">
In order to get to listen for that click, you have to go through the parent div since it's an original part of the DOM.
$('#loaded').on('click', '#someButton', function () {
//do something
});

How to create comma separated list from multiple select elements Javascript

I have a form of dynamically created single option select elements. What I need to do is create a list of all of the selected indexes of these elements, separated by a comma. I'm using
elements = document.getElementsByClassName("my-class");
to grab a node list (whatever one of those is, I'm guessing like an array?) of all of the select elements, and I know about .selectedindex, but I'm stuck from there.
I would like to get an output like:
3,4,6,1
I want to use this data in a query string to do some magic.
Any help is appreciated.
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
you just need to convert nodeList to array.
and you can get more info about it here: https://davidwalsh.name/nodelist-array
below is the full working code.
notice the extra button i add and getValue() method =)
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select name="cat" id="cat-drop-id" class="som-changecat-category-dropdown">
<option value="-1">Select category</option>
<option class="level-0" value="1">test</option>
<option class="level-0" value="2">test2</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
<button onClick="getValue(event)">get comma seperated value</button>
</form>
<script>
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
var counterid = counter;
var newdivid = "dynamic-div-"+counterid;
newdiv.setAttribute("id", newdivid);
oldelement = document.getElementById('cat-drop-id');
newelement = oldelement.cloneNode(true);
newdiv.innerHTML = "<br><select name='cat' id='cat-dropdown-id" + counterid + "' class='som-changecat-category-dropdown'>" + newelement.innerHTML + "</select><input type='button' id='remove-button-id" + counterid + "' value='Remove DUMMY' onclick='removeDummy(this.id);' /><br><br>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
function removeDummy(elementtoremove) {
var elem = document.getElementById(elementtoremove);
elem.parentNode.parentNode.removeChild(elem.parentNode);
return false;
}
function getValue(event) {
event.preventDefault();
// all select element.
var selects = document.getElementById('dynamicInput').querySelectorAll('select');
// convert nodeList to array
var selectsArray = Array.prototype.slice.call(selects)
// now you can use Array.prototype.*
var result = selectsArray.map(select => {
return select.value;
}).join(',');
// do what ever you want with `result` now.
console.log(result);
return result;
}
</script>
As .selectedOptions is still isn’t safe to go with there is nothing more than to iterate the options of each select and get the selected ones. Try something like:
var selects = document.getElementsByClassName('som-changecat-category-dropdown');
var values = {}, select, id, optionValues;
for (var i = 0; i < selects.length; i++) {
select = selects[i];
id = select.id;
optionValues = [];
for (var j = 0; j < select.options.length; j++) {
var option = select.options[j];
if (option.selected) optionValues.push(option.value);
}
values[select.id] = optionValues.join(',');
}
// gives you an object with the selects’ ids as keys
//and the komma separated values as value
document.write(JSON.stringify(values));
<form action="?page=test-options-page&something=0" method="POST">
<div id="dynamicInput">
<select multiple id="cat-dropdown-1" class="som-changecat-category-dropdown">
<option value="1" selected>bli</option>
<option value="2">bla</option>
<option value="3" selected>blu</option>
</select>
<select multiple id="cat-dropdown-2" class="som-changecat-category-dropdown">
<option value="4">blimm</option>
<option value="5" selected>blamm</option>
<option value="6" selected>blumm</option>
</select>
</div>
<input type="button" value="Add another dropdown" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
You could make this work to collect all the form elements’ values and use the resulting object as a base for creating your query string.

Javascript - added Orange once in fruitslist drop down list

<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected)
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
From above code, first I select Orange from drop down list and click >> button, the Orange value will added in fruitslist drop down list. After that. I select Orange again from drop down list and click >> button, the Orange value will added again in fruitslist drop down list. However, I just want the Orange value added in fruitslist drop down list once. How should I modify it? Can someone help me?
Here is the fix.
<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected && !isAddedAlready(document.getElementById("fruits").options[i].text))
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
function isAddedAlready(text) {
var fruitslist = document.getElementById("fruitslist");
if(fruitslist.length ==0) return false;
for(var i=0; i<fruitslist.length; i++) {
if(fruitslist.options[i].text === text) return true;
}
return false;
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
Try changing your addFruits function to the following:
function addfruits()
{
for (var i = 0; i < document.getElementById("fruits").options.length; i++)
{
if (document.getElementById("fruits").options[i].selected)
{
var optionText = document.getElementById("fruits").options[i].text;
var fruitslist = document.getElementById("fruitslist");
var found = false;
//Does the item clicked on already exist in the destination list?
for (var j = 0; j < fruitslist.length; j++) {
if (fruitslist[j].text == optionText) {
found = true;
break;
}
}
//If the item does not exist, add it to the list.
if (!found) {
var option = document.createElement("option");
option.text = optionText;
fruitslist.add(option);
}
}
}
}
The important thing to do here is first check that the fruitslist does not contain the item that was clicked on, hence that additional for-loop.

How do I clone a fieldset without transfering the values

I am atempting to clone a fieldset that has selects without cloning the inputs. (I need blanks). I have created a hidden fieldset in the body of the form but not the form itself but I can't seem to get it to work
<div id="analyte" style="display: none">
<div class="_40">
<label class="analyte-label" for="analyte">Analyte:</label>
<input class="analyte" type="text" id="analyte1" name="analyte" value=""> </div>
<div class="_30">
<label class="preserved-label" for="preserved">Preserved</label>
<select class="select_preserved" id="preserved1" name="preserved" data-iconpos="left" data-icon="grid" data-native-menu="false" >
<option value = ""></option>
<option value = "HNO3">HNO₃</sub></option>
<option value = "H2SO4">H₂SO₄</option>
<option value = "H3PO4">H₃PO₄</option>
<option value = "HCL">HCL</option>
<option value = "None1">None</option>
</select></div></div>
I am then using this code in the form
<input type="button" id="add_Analyte" onclick="add_Analyte" value="ADD ANALYTE" /></div>
<script>
$(document).ready(function() {
var _counter = 0;
function add_Analyte() {
_counter++;
var newFields = document.getElementById("Analyte").cloneNode(true);
newFields.id = "";
newFields.style.display = "block";
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById("addAnalyte");
insertHere.parentNode.insertBefore(newFields,insertHere);
}
})
</script>

Categories

Resources