I need an array of selected checkboxes - javascript

Javascript Code:
var simvalue = $('input[name="simnamecbx"]:checked').each(function() {
var sim_name=this.value.split(" ")[0];
console.log("simname:",sim_name);
var sim_list = [{
simulation_name : sim_name,
}];
console.log(sim_list);
});
I need an array of selected checkboxes in sim_list.. currently the array of values are replaced with the same index ie Array[1].. I need values like 1,2,3,4 in 'var simvalue'

Your are not pushing data to array instead you are re initiating array
try like this
var sim_list=[];
var simvalue = $('input[name="simnamecbx"]:checked').each(function() {
var sim_name=this.value.split(" ")[0];
console.log("simname:",sim_name);
sim_list.push({
simulation_name : sim_name,
});
});
console.log(sim_list);

You are reassigning the array instead of adding to it here
var sim_list = [{
simulation_name : sim_name,
}];
Also there should not be any , when setting only one property to an object or on the last property. You can use push to add to an array.
sim_list.push({simulation_name : sim_name});
with sim_list delcared as an empty array BEFORE the loop.
var sim_list = [];
$('input[name="simnamecbx"]:checked').each(function() {
var sim_name = this.value.split(" ")[0];
sim_list.push({
simulation_name : sim_name // comma removed to avoid errors
});
});
See push documentation

As others said, you are reassigning the array in each loop so all of the previous values are lost.
The map function can get all the values you want and put them into an array:
$(function() {
// Call map on your selector
var result = $('input[name="simnamecbx"]:checked').map(function() {
// return the values you want in the array
return { simulation_name: this.value.split(' ')[0] };
}).get(); // get returns the result as an array
// Output result
$.each(result, function(i, val) {
$('#result').append("Simulation name: " + val.simulation_name + "<br />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="simnamecbx" value="test1 1" checked="checked" /> 1 <br />
<input type="checkbox" name="simnamecbx" value="test2 2" /> 2 <br />
<input type="checkbox" name="simnamecbx" value="test3 3" /> 3 <br />
<input type="checkbox" name="simnamecbx" value="test4 4" checked="checked" /> 4 <br />
<input type="checkbox" name="simnamecbx" value="test5 5" /> 5 <br />
<div id="result"></div>

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">

How to create objects from multiple selectors in jquery?

I have two elements(#list1, #list2 in html). I need to create object and populate it from these two elements.
For example:
$('#list1, #list2').each(function(index,value){
var object =[ {#list1.value, #list2.value} ];
})
Something like that. So it can add these elements to array with each iteration. How it can be done?
it is .val()
you can push OR you can map
You can use a class so you do not need to list
NOTE: If there is no value attribute on the field, using this.getAttribute("value") on the .get examples will result in any field without value attribute to be omitted from the array instead of adding an empty value (Thanks #adz5A)
http://jsfiddle.net/mplungjan/jLsa80m9/7/
var object1 = [];
$('#list1, #list2').each(function() {
object1.push($(this).val())
})
console.log(object1);
// Smarter:
var object2 = $('#list1, #list2')
.map(function(index,$list) {
return $list.value; // or this.value or $(this).val();
})
.get();
console.log(object2);
// EVEN Smarter:
var object3 = $('.list')
.map(function() {
return this.value;
})
.get();
console.log(object3);
// The two following versions were posted by #rmn - I include them here for
// completeness sake. Upvote his answer if you like them
// ES6 with jQuery
var object4 = $('#list1, #list2').get().map(el => el.value)
console.log(object4);
// ES6 without jQuery
var object5 = [...document.querySelectorAll('#list1, #list2')].map(el => el.value)
console.log(object5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="value1" id="list1" class="list" />
<input type="text" value="value2" id="list2" class="list" />
I think you are looking for .get(). It returns as an array the set of matched DOM elements. You can easily combined this with map to retrieve the value of some attribute for instance
$("selector").map(function () { return this.getAttribute("value"); }).get();
Will get you the value attribute for the selection into an array. Note that you can use arrow function inside map as the second argument is the dom node itself, in my example the dom element is bounded to the lexical context this.
With jQuery
$('#list1, #list2').get().map(el => el.value)
Without jQuery
[...document.querySelectorAll('#list1, #list2')].map(el => el.value)
you can create array outside the loop and push it on each iteration
var object =[];
$('#list1, #list2').each(function(){
object.push($(this).val());
});
If you want to have id in your object, this is better:
function getList(){
var list = []
$("#input1, #input2").each(function(){
list.push({id: this.id, value: this.value });
});
console.log(list);
/*
OUTPUT:
[
{
"id": "input1",
"value": "v1"
},
{
"id": "input2",
"value": "v2"
}
] */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text" value="v1" />
<input id="input2" type="text" value="v2" />
<input type="button" onclick="getList()" value="get list" />

Jquery checkboxes return some values

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>

javascript multidimensional array creation and insertion

Hello I want to create an array in javascript
var sortValues = array(
2 => array(3,4,5),
3 => array(5,6,7),
12 => array (7,4,5)
);
Now I am looping through all textboxes of my form. Every textbox has id like 2_3 means 2 will be the main index of the array.
My html markup looks like
<input type="text" value="3" id="2_5" name="2_5">
<input type="text" value="4" id="2_5" name="2_6">
<input type="text" value="5" id="2_5" name="2_7">
<input type="text" value="5" id="3_1" name="3_1">
<input type="text" value="6" id="3_2" name="3_2">
..................................
Now I want to check if 2 exists in array sortValues, I will take the value of the text box and and will check if this value exists in the array against 2 then I will put an alert that value already exists, if value doesn't exists push the value in sub array. Means I need to put 3 against 2 I will check if 3 exists against 2, if yes put alert else push in array.
If 2 (main index) doens't exist create a new index in array and so on. I have tried so far
var sortvalues = new Array();
$(":text").each(function () {
if($(this).val() != '') {
id = $(this).attr('id');
ids = id.split("_");
parent = ids[0];
child = ids[1];
if(typeof sortvalues[parent] !== 'undefined') {
if(typeof sortvalues[parent][$(this).val()] !== 'undefined') {
alert("Value already exists");
} else {
sortvalues[parent][] = $(this).val();
}
} else {
sortvalues.push(parent);
}
}
});
console.log(sortValues);
Which gives ["2", "2", "2"] which is wrong. Can Any body guide me how can I achieve above mentioned array in above mentioned criteria ??/
Do you mean to create an array in another array?
For example :
var sortValues = new Array();
sortValues[2] = Array(3,4,5);
Please clarify your question. And the following:
sortvalues[parent][] = $(this).val() --> you can't leave empty for the second array.

How To copy object by value using jquery

Hello I'm having an issue with this check box :
<input type="checkbox" id="hideTempSeries" checked="checked" value="0" />
Temperature <br />
<input type="checkbox" id="hideFlowSeries" checked="checked" value="1" />
Flow <br />
<input type="checkbox" id="hidePressSeries" checked="checked" value="2"/>
Pressure <br />
<input type="checkbox" id="hideCondSeries" checked="checked" value="3" />
Conductivity <br />
.. and this jQuery function that sends an array of this check box values to a function called
removePanes(checkedArray) " every time any of the check boxes have changed "
$("#tools :checkbox").change(function(){
if($(this).prop('checked')){// when Checked
}
else{// when unChecked
var checkedArray = [] ;
$("#tools :checkbox").each(function(index,value){
if($(this).prop('checked') == false){checkedArray.push($(this).val())}
});
removePanes(checkedArray) ;
}
removePanes() function
function removePanes(id){
var removeUncheckedSeries = $.map(newSeries , function(index,value){
for(var i=0 ; i < id.length ; i++){
if(index.yAxis == id[i])return null;
}
return index ;
});
var modified = $.map(removeUncheckedSeries, function(index,value) {
index.yAxis = 15 ;
return index ;
});
console.log(modified) ;
} ;
this is newSeries[] Object
The removePanes(checkedArray) function then takes this array and removes all the objects equivalent to the unchecked values from : newSeries[] object
Then it sets all the yAxis values equal to 15.
This function is not working.
Because each time the check box changed the function doesn't reload the newSeries[] object it just modifies it on the last change.
What it does is, the first click works fine and then it set all the yAxis to 15. When I unchecked any other boxes since all the yAxis equal to 15 and the jQuery array send value from 0 to 3 nothing happened.
QUESTION: How can i make the removePanes(checkedArray) reload with the newSeries[] object each time a change on check box trigger?
That is happening because objects are by default copied by reference
in Javascript.
So if you change any property of copied object from anywhere it will affect all others. To copy an object by value only(or clone) you can use jQuery's $.extend() method like Jonh Resig(Yes he himself) showed here https://stackoverflow.com/a/122704/344304
var newObj = $.extend(true, {}, oldObj); // deep copy
So change your removePanes function like following
function removePanes(id) {
var seriesCopy = jQuery.extend(true, {}, newSeries);
var removeUncheckedSeries = $.map(seriesCopy, function(obj, index) {
return $.inArray(obj.yAxis,id) == -1 ? obj : null;
});
var modified = $.map(removeUncheckedSeries, function(obj, index) {
obj.yAxis = 15;
return obj;
});
console.log(modified);
};​
Demo: http://jsfiddle.net/joycse06/w2KS2/

Categories

Resources