Unchecked input checkbox with identical ids - javascript

I'm trying to get the values of an input of type checkbox with the same ID, and try to get the click (the checked), to the one with the value 1
but when I do the console.log I only get the value of the first input and it does not get both values.
i.e. to bring me the value number 2 of the first one and not 2 and 1.
<script>
var s = document.getElementById("switchA").value;
console.log(s);
</script>
These inputs are of checkbox type so if one of them has value two it should be unchecked.
<input type="checkbox" name="asd" id="switchA" value="2">
<input type="checkbox" name="asdf" id="switchA" value="1">

You shouldn't be giving the same id to multiple elements on a page. However, assuming you are not able to change the HTML, you can use the following to select multiple elements with the same id:
var s = document.querySelectorAll("[id='switchA']");

You should use a name or class instead to group the checkboxes. Ids are meant to be unique in a document.
const vals = [...document.querySelectorAll('input[type=checkbox][name=someName]')]
.map(x => x.value);
console.log(vals);
<input type="checkbox" name="someName" value="2">
<input type="checkbox" name="someName" value="1">
However, you could use an attribute selector to obtain all elements with a specific id, but that is not recommended.
const vals = [...document.querySelectorAll("[id=switchA]")]
.map(x => x.value);
console.log(vals);
<input type="checkbox" name="asd" id="switchA" value="2">
<input type="checkbox" name="asdf" id="switchA" value="1">

Related

Unable to get the value of radio buttons

I am not able to get second and third radio buttons values.
my code just gives me the first radio button value when I select this.
this is my radio buttons and the function by which I want to store the value of the radio button.
<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced" name="Q0_choice" value="2">
<input type="radio" id="choiced" name="Q0_choice" value="iii">
next.onclick = function () {
if (document.getElementById('choiced').checked) {
ans = document.getElementById('choiced').value;
}
}
This is because ID values must be unique - so it's grabbing the first element on the page it finds with the ID of choiced. You'll want to give each a unique ID, and you can use the name attribute for grouping radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
Try
document.querySelector('#choiced:checked')
This query return checked radio button.
You should not have the same ID for those inputs:
<input type="radio" id="choiced" name="Q0_choice" value="one">
<input type="radio" id="choiced2" name="Q0_choice" value="2">
<input type="radio" id="choiced3" name="Q0_choice" value="iii">
Then to get the selected you have to get them by it's name property. You can loop to check which one is selected.
next.onclick = function () {
const radios = document.getElementsByName('Q0_choice');
radios.forEach((radio) => {
if (radio.checked){
console.log(radio.value);
}
})
}

POST unchecked checkboxes with values to Node [duplicate]

I have an HTML form with an array of checkboxes (using [] naming). I need to be able to process this with express. I'm using body-parser.
The problem is that unchecked checkboxes don't submit a value, and at the same time, body-parser seems to remove "holes" in arrays by simply packing the values into an array in order of indices, but ignoring the indices themselves. (Update: Actually it looks like qs is the culprit).
Consider this full example, which displays a form and responds with a JSON dump of the submitted data:
Install:
npm install express body-parser
index.js:
var express = require("express");
var site = express();
site.use(require("body-parser").urlencoded({extended:true}));
site.get("/", function (req, res) {
res.sendFile(__dirname + "/test.html");
});
site.post("/form", function (req, res) {
res.json(req.body);
});
site.listen(8081);
test.html:
<html>
<body>
<form method="post" action="/form">
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1"><br>
<input type="text" name="text[0]"><br>
<input type="text" name="text[1]"><br>
<input type="text" name="text[2]"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
In that example, if I were to check only option[1], I verify that the index is set correctly by inspecting the request in Chrome, body is:
option[1]:1
text[0]:
text[1]:
text[2]:
Yet body-parser collapses the option array and produces the following in req.body:
{"option":["1"],"text":["","",""]}
As you can see, text has all three, but option has only one item. Similarly, if I were to check option[0] and option[2], the request body would look like:
option[0]:1
option[2]:1
text[0]:
text[1]:
text[2]:
But it would be parsed to:
{"option":["1","1"],"text":["","",""]}
I lose all information about which checkbox was checked.
My question is, how do I do this? What I want to happen is, e.g.:
With checkbox[1] checked:
{"option":[null,"1",null],"text":["","",""]}
With checkbox[0] and checkbox[2] checked:
{"option":["1",null,"1"],"text":["","",""]}
I'm not actually married to null and "1", I just need falsey and truthy.
Also, it is important that I not lose information about how many checkboxes should be in the array. For example, if I were to give each checkbox a unique value, I suppose I could translate "option":["0","1"] into an array of boolean values, except I would lose the knowledge that the array is of size 3 (with the 3rd value false in that case) -- although I guess I could add e.g. a hidden input like numberOfCheckboxes=3, but... this kind of mapping is cumbersome and I'd like to avoid it if possible.
My approach requires no javascript on client side.
Add hidden fields as many as your checkboxes with same names
body parser will parse checked items as array and string others
I meant
<input type="hidden" name="option[0]" value="0">
<input type="hidden" name="option[1]" value="0">
<input type="hidden" name="option[2]" value="0">
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">
If your option[1] is checked then body parser will parse it like
{option:['0', ['0', '1'], '0']}
And here is the modifier
req.body.option = req.body.option.map(item => (Array.isArray(item) && item[1]) || null);
so now body will be
{option: [null, '1', null]}
The simplest solution (not the best) is that you can add hidden input's with different ids and then check them when the check-boxes on the page get unchecked.
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[0]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[1]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[2]" value="1">
And before submit:
$('input[name^=option]').each(function () {
if(!this.checked) {
var name = "input[name=\'hiddenOption" + this.name.replace('option', '') + "\']";
console.log(name);
$(name).prop('checked', true);
}
});
And then based on that you can figure out which ones are not ticked.
https://plnkr.co/edit/mJCbtgQnQudHGrUzAz3A?p=preview

Express body-parser handling checkbox arrays on forms

I have an HTML form with an array of checkboxes (using [] naming). I need to be able to process this with express. I'm using body-parser.
The problem is that unchecked checkboxes don't submit a value, and at the same time, body-parser seems to remove "holes" in arrays by simply packing the values into an array in order of indices, but ignoring the indices themselves. (Update: Actually it looks like qs is the culprit).
Consider this full example, which displays a form and responds with a JSON dump of the submitted data:
Install:
npm install express body-parser
index.js:
var express = require("express");
var site = express();
site.use(require("body-parser").urlencoded({extended:true}));
site.get("/", function (req, res) {
res.sendFile(__dirname + "/test.html");
});
site.post("/form", function (req, res) {
res.json(req.body);
});
site.listen(8081);
test.html:
<html>
<body>
<form method="post" action="/form">
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1"><br>
<input type="text" name="text[0]"><br>
<input type="text" name="text[1]"><br>
<input type="text" name="text[2]"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
In that example, if I were to check only option[1], I verify that the index is set correctly by inspecting the request in Chrome, body is:
option[1]:1
text[0]:
text[1]:
text[2]:
Yet body-parser collapses the option array and produces the following in req.body:
{"option":["1"],"text":["","",""]}
As you can see, text has all three, but option has only one item. Similarly, if I were to check option[0] and option[2], the request body would look like:
option[0]:1
option[2]:1
text[0]:
text[1]:
text[2]:
But it would be parsed to:
{"option":["1","1"],"text":["","",""]}
I lose all information about which checkbox was checked.
My question is, how do I do this? What I want to happen is, e.g.:
With checkbox[1] checked:
{"option":[null,"1",null],"text":["","",""]}
With checkbox[0] and checkbox[2] checked:
{"option":["1",null,"1"],"text":["","",""]}
I'm not actually married to null and "1", I just need falsey and truthy.
Also, it is important that I not lose information about how many checkboxes should be in the array. For example, if I were to give each checkbox a unique value, I suppose I could translate "option":["0","1"] into an array of boolean values, except I would lose the knowledge that the array is of size 3 (with the 3rd value false in that case) -- although I guess I could add e.g. a hidden input like numberOfCheckboxes=3, but... this kind of mapping is cumbersome and I'd like to avoid it if possible.
My approach requires no javascript on client side.
Add hidden fields as many as your checkboxes with same names
body parser will parse checked items as array and string others
I meant
<input type="hidden" name="option[0]" value="0">
<input type="hidden" name="option[1]" value="0">
<input type="hidden" name="option[2]" value="0">
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">
If your option[1] is checked then body parser will parse it like
{option:['0', ['0', '1'], '0']}
And here is the modifier
req.body.option = req.body.option.map(item => (Array.isArray(item) && item[1]) || null);
so now body will be
{option: [null, '1', null]}
The simplest solution (not the best) is that you can add hidden input's with different ids and then check them when the check-boxes on the page get unchecked.
<input type="checkbox" name="option[0]" value="1">
<input type="checkbox" name="option[1]" value="1">
<input type="checkbox" name="option[2]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[0]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[1]" value="1">
<input type="checkbox" class="hidden" name="hiddenOption[2]" value="1">
And before submit:
$('input[name^=option]').each(function () {
if(!this.checked) {
var name = "input[name=\'hiddenOption" + this.name.replace('option', '') + "\']";
console.log(name);
$(name).prop('checked', true);
}
});
And then based on that you can figure out which ones are not ticked.
https://plnkr.co/edit/mJCbtgQnQudHGrUzAz3A?p=preview

How to insert value of checked checkbox in array using jQuery

I want select all input values that is checked and has name DisbursementUnitCodes
$('input:checked[name=DisbursementUnitCodes]').val()
This code give the first element value but i want give all input value to list or array.
Use .each() to iterating selected elements and get value of its.
var arr = [];
$("input:checked[name=DisbursementUnitCodes]").each(function(){
arr.push($(this).val());
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="DisbursementUnitCodes" value ="A" checked />
<input type="checkbox" name="DisbursementUnitCodes" value ="B" />
<input type="checkbox" name="DisbursementUnitCodes" value ="C" checked />
<input type="checkbox" name="other" value ="D" checked />
<input type="checkbox" name="other" value ="E" />
.val() gives you value of first element in selection. If you want all values in array, you should use .map() like this:
var values = $('input:checked[name=DisbursementUnitCodes]').map(function() {
return $(this).val();
}).get();

Javascript: How can I get all value of selected checked checkboxes, push to an array then put in in a input HTML element?

I have a list of 50 checkboxes. If users check some of them, how can I get all values of the selected ones and push them into an array then place it in a hidden text element?
Can I use the same name for all checkboxes? or I must use different name for each of them?
<input type="checkbox" name="bulk_id[]" value="1"/>
<input type="checkbox" name="bulk_id[]" value="2"/>
<input type="checkbox" name="bulk_id[]" value="3"/>
<input type="checkbox" name="bulk_id[]" value="4"/>
<input type="checkbox" name="bulk_id[]" value="5"/>
...
Thank you.
You tagged your question with jquery, so i'll assume you are using it.
You select checkbox with input[type=checkbox] and use the subclass :checked to filter checked ones
1- get all checked boxes in an array
var selectedValues =[]
$('input[type=checkbox]:checked').each(function(i,e){
selectedValues.push( $(e).attr('value') )
})
2- append the content of this array in a hidden input (separated by ,)
$('#yourhiddenID').val( selectedValues.join(',') );
In this solution the name of your checkboxes does not matter.
Put your checkboxes in a container for a better selection :
$('#yourCheckboxContainerID input[type=checkbox]:checked')
so you have to get all checkboxes you have
var checkboxes = document.getElementsByName("bulk_id[]");
var arrayVal = [];
for (var i= 0; i<checkboxes.length;i++)
{
if (checkboxes[i].checked === true)
{
arrayVal.push(checkboxes[i].value);
}
}

Categories

Resources