How to get the value of multiple checkboxes only - javascript

I am trying to get the value of multiple checkboxes, but I also have radio buttons included. I try to get the value like this:
const inputData = [];
document.querySelectorAll("input:checked").forEach((item) => {
inputData.push(item.value);
});
As a result, I get the values of both the radio buttons and the checkboxes.
This is how I created the radio buttons and the checkboxes:
else if (i.type === "single-select"){
for (const o of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "radio");
x.setAttribute("id", "radioID");
x.value = o;
const y = document.createElement("LABEL");
const t = document.createTextNode(o);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("radioButton").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
}
else if (i.type === "multi-select"){
for (const l of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.value = l;
const y = document.createElement("LABEL");
const t = document.createTextNode(l);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("checkbox").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
}
How can I get the values of multiple checkboxes only, without getting the values of the radio buttons?

Change your selector to be more targeted.
"input:checked"
to
"input[type=checkbox]:checked"

Related

How to define the name of a radio button and get its checked value

I am trying to get the value of a radio button as JSON. This is my code:
for (const o of i.options){
const x = document.createElement("INPUT");
x.setAttribute("type", "radio");
x.setAttribute("id", "radioID");
x.name = RadioBtn;
const y = document.createElement("LABEL");
const t = document.createTextNode(o);
y.appendChild(t);
const div = document.createElement("div");
div.style.height = "5px";
div.appendChild(x);
div.appendChild(y);
document.getElementById("radioButton").appendChild(div);
window.data.appendChild(x);
window.data.appendChild(y);
window.data.appendChild(div);
}
const fifthQuestion = JSON.stringify($("input[name=RadioBtn]:checked").val());
console.log(fifthQuestion);
I get the following errors:
1. ReferenceError: RadioBtn is not defined
2. ReferenceError: $ is not defined
I seem not to be defining the name of the radio button the right way. How can I do that and get the input of the checked radio button?

Array reversed when it's sent using the form

I'm sending 3 arrays with checkboxes (checked and not) using a form to a PHP page, trying to do an Insert in a MySQL database. When I send an array with length = 1, it inserts just fine, but arrays with length superior to 1 are shown (and insert) reversed when 2 or 3 checkboxes are checked, occupying index 0 of the array, being that it was at index 1 at first.
I'm using WAMP 3.1.7 64 bits, PHP 7.2.14 and Brackets. The arrays are called "electricidad", "proyector" and "wifi". I create the checkboxes with a button using the function nuevaSala (element), function checkboxElegido() is to change the value of checked checkboxes (no is the default).
<script>
var instancia = 0;
function nuevaSala(element){
instancia++;
var newDiv = document.createElement("DIV");
newDiv.name = "nuevasSalasDiv[]";
newDiv.id = "nuevasSalas"+instancia;
var newLabel = document.createElement("LABEL");
newLabel.id = "Sala"+instancia;
newLabel.innerHTML = "Sala "+instancia;
var newInput = document.createElement("INPUT");
newInput.id = "sala"+instancia;
newInput.name = "nombreSala[]";
newInput.type = "text";
var newLabel1 = document.createElement("LABEL");
newLabel1.id = "Capacidad"+instancia;
newLabel1.innerHTML = "Capacidad";
var newInput1 = document.createElement("INPUT");
newInput1.id = "capacidad"+instancia;
newInput1.name = "capacidad[]";
newInput1.type = "number";
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.name = "electricidad[]";
newCheckbox.id = "electricidad"+instancia;
newCheckbox.value = "no";
newCheckbox.setAttribute("onclick", "checkboxElegido()");
newCheckbox.setAttribute("style", "float: right");
var newCheckbox1 = document.createElement("input");
newCheckbox1.type = "checkbox";
newCheckbox1.name = "wifi[]";
newCheckbox1.id = "wifi"+instancia;
newCheckbox1.value = "no";
newCheckbox1.setAttribute("onclick", "checkboxElegido()");
newCheckbox1.setAttribute("style", "float: right");
var newCheckbox2 = document.createElement("input");
newCheckbox2.type = "checkbox";
newCheckbox2.name = "proyector[]";
newCheckbox2.id = "proyector"+instancia;
newCheckbox2.value = "no";
newCheckbox2.setAttribute("onclick", "checkboxElegido()");
newCheckbox2.setAttribute("style", "float: right");
var newLabelElec = document.createElement("LABEL");
newLabelElec.innerHTML = "Electricidad";
newLabelElec.setAttribute("style", "float: right");
var newLabelProy = document.createElement("LABEL");
newLabelProy.innerHTML = "Proyector";
newLabelProy.setAttribute("style", "float: right");
var newLabelWifi = document.createElement("LABEL");
newLabelWifi.innerHTML = "Wifi";
newLabelWifi.setAttribute("style", "float: right");
document.getElementById("salaId").appendChild(newDiv);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabel);
document.getElementById("nuevasSalas"+instancia).appendChild(newInput);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabel1);
document.getElementById("nuevasSalas"+instancia).appendChild(newInput1);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelElec);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelProy);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox2);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelWifi);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox1);
document.getElementById("nuevasSalas"+instancia).appendChild(document.createElement("BR"));
}
</script>
<script>
function checkboxElegido(){
var proy = document.getElementsByName("proyector[]");
var wifi = document.getElementsByName("wifi[]");
var elec = document.getElementsByName("electricidad[]");
function valores(item){
if(item.checked){
item.setAttribute("value", "si");
} else if(!item.checked){
item.setAttribute("value", "no");
}
}
proy.forEach(valores);
wifi.forEach(valores);
elec.forEach(valores);
}
</script>
If the array has lenght 2, and the checked checkbox is "electricidad" in index 0 and checked in index 1 are "wifi", "electricidad" and "proyector", I expect this:
[0] = "electricidad" => si, "wifi" => no, "proyector" => no
[1] = "electricidad" => si, "wifi" => si, "proyector" => si
but I got this:
[0] = "electricidad" => si, "wifi" => si, "proyector" => si
[1] = "electricidad" => si
Beforehand, thank you!

How to add a line break after each dynamically created checkbox?

Here's the code for the dynamically created checkboxes. How do I add line breaks to the code so that I have one checkbox per line? I tried to do document.createElement("br") and appending it after get.appendChild(label) but it didn't work.
function setCheckboxes(browser) {
var get = document.getElementById("get");
if (browser == "courses") {
for (var i = 1; i < coursesGetKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = coursesGetKeys[i];
checkBox.name = "r";
label.textContent = setOpt(coursesGetKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}
if (browser == "rooms") {
for (var i = 1; i < validRoomsKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = validRoomsKeys[i];
checkBox.name = "r";
label.textContent = setOpt(validRoomsKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}
};
You already know how to create an input:
var checkBox = document.createElement("input");
and how to append it:
get.appendChild(checkBox); // get is the parent element you selected at the top of your code
So your first hunch was correct, you can also do this:
var br = document.createElement("br");
get.appendChild(br);
which creates a br element, and then also appends it to the "get" parent.

innerHTML not showing up when added input element dynamically

I am trying to add an <input> element using Javascript. However, the innerHTML is not showing up. Below is my code:
function addElements()
{
container = document.getElementById("duration"); //a div container
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
input1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
input2.innerHTML = "months";
container.appendChild(input1);
container.appendChild(input2);
}
The result of this code only produces two number input fields without the innerHTML. Is there anything wrong with my code?
Input elements don't have inner content you can set with innerHTML. Instead set value property:
input1.value = "years";
However, it seems that in your case you want to set placeholder:
input1.setAttribute("placeholder", "years");
or you can set corresponding property as well:
input1.placeholder = "years";
I think what you try to achieve is [label][input] in this case you have to add 2 new more elements on page.
function addElements()
{
container = document.getElementById("duration"); //a div container
var label1 = document.createElement("label");
var input1 = document.createElement("input");
var label2 = document.createElement("label");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
label1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
label2.innerHTML = "months";
container.appendChild(label1);
container.appendChild(input1);
container.appendChild(label2);
container.appendChild(input2);
}
addElements();
<div id="duration" />

Javascript -> Attempting to dynamically add radio buttons from an array

So I'm working on my very first 'real' JavaScript project -> the famed Quiz app :)
I'm passing questions and answers via an array, and I want make sure to allow for a variable number of answer options. To do this, I'm using a For loop and the createElement method to add and populate the appropriate HTML for each answer in the array. To my eyes, what I've built actually works great. And after running the function I can see the resultant HTML elements in the right place and with all the appropriate tagging in my console. However, the inner DIV text won't render on screen! Very confused. What am I missing? Please help!
My JS code:
<body>
<form id="form1">
</form>
<script>
var answers = ["answer1", "answer2", "answer3", "answer4", "answer5"];
function createRadioButtonFromArray(array) {
var len = array.length;
var form = document.getElementById("form1");
for (var i = 0; i < len; i++){
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
form.appendChild(radio);
radio.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
}
}
</script>
</body>
And here's a screenshot of my console AFTER I run the function, for reference:
You're plan is nearly working but Input elements have no content! So the div's will not be rendered at all!
Create a div that contains your radio button and the input text on the same level:
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("div");
radioText.id = "c" + i;
radioText.class = "choiceText";
radioText.innerHTML = array[i];
radioText.appendChild(radio);
form.appendChild(radioText);
Add label after or before radio button. Label will let you check radio button by clicking on it's text
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices";
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var radioText = document.createElement("label");
radioText.id = "c" + i;
radioText.setAttribute("for", "choice" + i);
radioText.class = "choiceText";
form.appendChild(radio);
form.appendChild(radioText);
document.getElementById("c" + i).innerHTML=array[i];
<input> cannot contain any DOM elements or DOM nodes. But if you want to have checkboxes associated with some text, I suggest you to use <input> with <label for=""> where label.for is name of input element. For combining them you can put them into some container(i.e. <div>):
By default on label with set property for raises click event on element with the same name property value as for property value. This means that you do not need to add additional click event handlers for <label> elements.
var checkId = 1;
var container = document.createElement("div");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = "choices"+checkId;
radio.class = "radioButtons";
radio.value = i;
radio.id = "choice" + i;
var label = document.createElement("label");
label.innerHTML = array[i];
// Set attribute for
label.setAttribute("for","choices"+checkId);
//Increase counter for check element name.
checkId++;
container.appendChild(radio);
container.appendChild(label);
form.appendChild(container);

Categories