javascript multidimensional array creation and insertion - javascript

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.

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 remove unchecked value from list?

I need to get all checked values from checkboxes and return them in element.
I have a code:
this.values = [];
if (item.checked) {
this.values.push(item.value);
} else {
this.values.splice(item.value)
}
return alert(this.values);
There are few problems:
If I check and uncheck the same item, it pushes to array every time, so there could be same multiple values. (this.values = [1,1,1])
Splice does not remove from this.values one item.value that was unchecked, it removes all values and make this.values empty (this.values = []);
What I need is:
if I have item values for example: 1 , 2 , 3
And check every item, that my array will become - this.values = [1 , 2 , 3]
If I uncheck item number 2, this.values = [1, 3]
Use a common class for all the checkbox, then use document.querySelectorAll to get the checkbox and attach event listener to each of the box.
Now on change even call another function and first filter out the checked checkbox then use map to get an array of the check box value
let elem = [...document.querySelectorAll('.checkBox')]
elem.forEach(item => item.addEventListener('change', getChecked))
function getChecked() {
let getChex = elem.filter(item => item.checked).map(item => item.value)
console.log(getChex)
}
<input type="checkbox" value="1" id="one" class="checkBox">
<label for="one">1</label>
<input type="checkbox" value="2" id="two" class="checkBox">
<label for="two">2</label>
<input type="checkbox" value="3" id="three" class="checkBox">
<label for="three">3</label>
Ciao, you can do this:
this.values = [];
if (item.checked) {
if(!this.values.includes(item.value)) {
this.values.push(item.value);
}
} else {
if(indexOf(item.value) !== -1){
this.values.splice(this.values.indexOf(item.value), 1)
}
}
return alert(this.values);
Insert item.value only if this.values does not contains value and use splice with index (if item is in this.value).
since you didn't show your html file. I just posted the code works for me for your reference.
function getSelectedCheckboxValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
let values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
return values;
}
if you are editing js in the HTML,
replace
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
with
const checkboxes = document.querySelectorAll('input[name="color"]:checked');
source: https://www.javascripttutorial.net/javascript-dom/javascript-checkbox/

javascript modify variable

I have this:
var category = "3%2C16%2C6%2C10%2C1%2C19";
in witch category id are 3 16 6 10 1 19 and the %2C is the space between category.
What i want is here:
if (document.getElementById("3").checked = false) {
category = "16%2C6%2C10%2C1%2C19";
}
else {
category = "3%2C16%2C6%2C10%2C1%2C19";
}
I want to make this for all the checkbox that i have, but you can't deselect all the checkbox because the servers don't send you back any data.
This is for filtering the results
It would be easier to use an array, then convert it to this string representation, when needed.
var categories = [];
$('#category-form input').change(function () {
var id = $(this).attr('data-id'),
index = categories.indexOf(id);
if (this.checked && index === -1) {
categories.push(id);
} else if (!this.checked && index !== -1) {
categories.splice(index, 1);
}
});
You can see my working code in this fiddle.
(with multiple checkboxes, string representation, and at least one check)
Try
if (document.getElementById("3").checked === false) {
notice the extra double equals to do a typesafe check
or better still
if (!document.getElementById("3").checked) {
However, as you're using jQuery and you appear to be munging a string together from checked states, which is going to be really brittle with hardcoded strings so maybe something like:
var category = "";
$( "input:checked" ).each(function() {
category = $(this).id + "%2C";
};
Only calling that when you need the output e.g. button press.
As you are using jquery, you can listen to the change event for the checkboxes, then build the list each time one is checked or unchecked. To store the values you can either use the value attribute for the checkbox or add data- attributes.
Getting an array of values and joining them will avoid the trailing %2C.
var category = '';
(function($) {
// cache collection of checkboxes
var cboxes = $('input[type=checkbox]');
cboxes.on('change', function() {
// find the ticked boxes only, and make an array of their category values, then join the values by a space
category = $.makeArray(cboxes.filter(':checked').map(function() {
return $(this).data('category');
//return $(this).val(); // if you store them in value="3"
})).join('%2C');
// output for debug purpose
$('#categoryOutput').html("'" + category + "'");
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="c1" data-category="3" />
<input type="checkbox" id="c2" data-category="16" />
<input type="checkbox" id="c3" data-category="6" />
<input type="checkbox" id="c4" data-category="10" />
<input type="checkbox" id="c5" data-category="1" />
<input type="checkbox" id="c6" data-category="19" />
</form>
<div id="categoryOutput"></div>
Side Note: try to avoid starting element ids with numbers - it is technically invalid and can break things in some scenarios.

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/

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