Jquery checkboxes return some values - javascript

I have list of checkboxes and I need to get an array of checked items. I use the following function, but it returns some character values also.
var rIds = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
Output is:
["1", "414", "true", "true"]
However I expect the below output,
["1", "414"]
Why is this?

Number() will only return number if it is number otherwise 0 ,Infinity , NaN will return
var rIds = $('input[type=checkbox]:checked').map(function (_, el) {
var current = $(el).val();
if (Number(current) == current) return current ;
}).get();

As suggested by #Rory Mccrossan, your selector will fetch all checkboxes. You should rather update your selector to get proper elements.
Following is a basic implementation showing both cases:
$("#btnTest").on("click", function() {
var allChks = $('input[type=checkbox]:checked').map((i, v) => v.value).get();
var div2Chks = $(".container2 input[type=checkbox]:checked").map((i, v) => v.value).get();
console.log(allChks, div2Chks)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="container1">
<input type="checkbox" value="true" checked>Test
<input type="checkbox" value="true" checked>Test
</div>
<div class="container2">
<input type="checkbox" value="foo" checked>Foo
<input type="checkbox" value="bar" checked>Bar
</div>
<button id="btnTest">Get Value</button>

Related

html checkboxes associative array - how to access this array in javascript?

I'm trying to do this:
<input type="checkbox" name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
and get access to this array in javascript like this
1.
var myarr = document.getElementsByName('appliances');
alert('here ' + myarr);
result: alert shows "here [object NodeList]"
2.
var myarr = document.getElementsByName('appliances');
alert('here ' + myarr['grill']);
result: alert shows "here undefined"
How may I get access to this array?
Your elements all have different names as far as HTML is concerned, "appliances[microwave]", "appliances[coffee-machine]", etc. Those names are only special to certain software (for instance, PHP will handle them on a form submission).
You can find all elements whose name starts with appliances by using querySelectorAll with the selector input[name^=appliances]. Then you access the entries in that NodeList by index (0, 1, and 2):
const checkboxes = document.querySelectorAll("input[name^=appliances]");
for (let n = 0; n < checkboxes.length; ++n) {
console.log(`${checkboxes[n].name} checked? ${checkboxes[n].checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">
If you want to access them by the names in [], you could create an object and put them on the object as properties:
function getNamedElementObject(baseName) {
const result = {};
// NOTE: The next line assumes there are no `]` characters in `name`
const list = document.querySelectorAll(`[name^=${baseName}]`);
for (const element of list) {
const match = element.name.match(/\[([^]+)\]/);
if (match) {
const propName = match[1]
result[propName] = element;
}
}
return result;
}
const checkboxes = getNamedElementObject("appliances");
console.log(`checkboxes["microwave"].checked? ${checkboxes["microwave"].checked}`);
console.log(`checkboxes["coffee-machine"].checked? ${checkboxes["coffee-machine"].checked}`);
console.log(`checkboxes["grill"].checked? ${checkboxes["grill"].checked}`);
// You could also loop through by getting an array from `Object.values`:
for (const checkbox of Object.values(checkboxes)) {
console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">
Or you could use a Map:
function getNamedElementMap(baseName) {
const result = new Map();
// NOTE: The next line assumes there are no `]` characters in `name`
const list = document.querySelectorAll(`[name^=${baseName}]`);
for (const element of list) {
const match = element.name.match(/\[([^]+)\]/);
if (match) {
const propName = match[1]
result.set(propName, element);
}
}
return result;
}
const checkboxes = getNamedElementMap("appliances");
console.log(`checkboxes.get("microwave").checked? ${checkboxes.get("microwave").checked}`);
console.log(`checkboxes.get("coffee-machine").checked? ${checkboxes.get("coffee-machine").checked}`);
console.log(`checkboxes.get("grill").checked? ${checkboxes.get("grill").checked}`);
// You could also loop through via the iterator from the `values` method:
for (const checkbox of checkboxes.values()) {
console.log(`${checkbox.name} checked? ${checkbox.checked}`);
}
<input type="checkbox" checked name="appliances[microwave]">
<input type="checkbox" name="appliances[coffee-machine]">
<input type="checkbox" name="appliances[grill]">
<!-- A fourth one just to show that it won't get selected: -->
<input type="checkbox" name="something-else">

Return CheckBox True False Status With jQuery Map

I am creating dynamic CheckBoxes using jQuery and by default, those are set to false status. Something as follows:
<input type="checkbox" class="cbCheck" value="false" />
So you can see no value or id is assigned there. Is it possible to just retrieve the true/false based on CheckBox checked/unchecked status something as follows using jQuery mapping?
string = $('input[type=checkbox]:checked').map(function (i, elements) {
return elements; //Here the elements like true or false, instead of elements.value
});
alert(string.join(','));
Expected Output: true, false, false, true (Based on user selection)
You can use the checked property.
const string = Array.from($('input[type=checkbox]')).map(function(element) {
return element.checked; //Here the elements like true or false, instead of elements.value
});
console.log(string.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" checked/>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked/>
var checkboxes = [];
function createDynamicCheckBoxes() {
if (checkboxes.length != 0)
return;
var numberOfBoxes = parseInt(Math.random() * 10) + 1;
for (var i = 0; i < numberOfBoxes; i++) {
var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("value", "false");
var number = document.createElement('label');
number.innerText = "(" + (checkboxes.length+1) + ") ";
document.getElementById("container").appendChild(number);
document.getElementById("container").appendChild(checkbox);
document.getElementById("container").appendChild(document.createElement('br'));
checkboxes.push(checkbox);
}
}
function logValues(){
for(var i=0; i<checkboxes.length;i++){
console.log("Checkbox (" + (i+1) + ") is set to " + checkboxes[i].checked);
}
}
<button onclick="createDynamicCheckBoxes()">Generate Checkboxes</button>
<button onclick="logValues()">Log Values of Checkboxes</button>
<div id="container">
</div>
This is a pure JavaScript based snippet. You can do something like this!
The .checked property return check/uncheck status of checkbox. So you need to use it.
var string = $('[type=checkbox]').map(function (i, elements) {
return elements.checked;
}).toArray().join(",");
Also you can simplify the code
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
console.log(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked />
<input type="checkbox" class="cbCheck" />

jQuery Get data-attribute of all checkbox into a string

I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
Instead return $(this).val(); you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Select all radio buttons which are checked with prototype

I have several input elements which look like this:
<input type="radio" checked="checked" value="1" name="handle[123]" />
<input type="radio" checked="checked" value="2" name="handle[456]" />
The number inside the name attribute is an object id i need. Now what I want to do is:
Fetch all input which are of type="radio" and are checked with prototype
Put all ids and values in an associative array
...so the resulting array looks something like this:
array{ 1 => 123, 2 => 456 }
Any ideas?
Here's what I came up with:
var results = [];
document.body.select('input[type=radio]:checked').each(function (element) {
var object = {};
object[element.value] = element.name.match(/\d+/)[0];
results.push(object);
});
new Ajax.Request('/some_url', {
method: 'post',
parameters: results
});
Demo
To get the checked radio button given a form id, and the name of the radio group:
function RF(el, radioGroup) {
if($(el).type && $(el).type.toLowerCase() == 'radio') {
var radioGroup = $(el).name;
var el = $(el).form;
} else if ($(el).tagName.toLowerCase() != 'form') {
return false;
}
var checked = $(el).getInputs('radio', radioGroup).find(
function(re) {return re.checked;}
);
return (checked) ? $F(checked) : null;
}
var value = RF('form_id', 'radio_grp_name');
Hope it helps
$$('input:checked[type=radio]').each(function (ele) {
output[ele.name.match(/\d+/)[0]] = ele.value;
});
This would give the desired output using prototype

Categories

Resources