How To copy object by value using jquery - javascript

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/

Related

How to push values to input type hidden when clicked on radio button using jQuery?

I am getting values from one variable in array format so by using for loop it will iterate and when click on input type radio button each value with comma separated push to hidden field
I tried this but nothing gets inserted. How can I push those values to the hidden field?
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").push(id[i]); //values like 1,2 want to push in hidden field when click on radio button
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="" />
<input type="radio" name="radion_btn2" value="" />
As per your code. for(var i = 0; i < id.length; i++) { run two times and whenever your event occur. At that time i value come 2 and id[2] comes undefined. Below code should work.
var id = ["1", "2"]; // getting this value from another varaible in array format
arrayData = [];
for (var i = 0; i < id.length; i++) {
$("input[name=radion_btn" + id[i] + "]").change(function() {
console.log($(this).val());
arrayData.push($(this).val()); //values like 1,2 want to push in hidden field when click on radio button
$('.selected_val').val(arrayData.join());
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" name="selected_val[]" value="" class="selected_val" />
<input type="radio" name="radion_btn1" value="1" />
<input type="radio" name="radion_btn2" value="2" />
You can simulate a push by adding the hidden input's value before the new value
var id = ["1", "2"]; // getting this value from another varaible in array format
for (var i = 0; i < id.length; i++) {
$(".selected_val").val("");
$("input[name=radion_btn" + id[i] + "]").change(function() {
$(".selected_val").val((i == 0 ? "" : ",") + $(".selected_val").val() + id[i]);
});
}
Here's an example of one approach that might help. See comments in snippet below.
let obj = {}; // create an empty object to store the clicked values
$(".radio").change(function() { // when a radio button is clicked
obj[this.id] = $(this).val(); // store it in the object
$(".selected_val").val(JSON.stringify(obj)); // and add the object to hidden field as string
console.log($(".selected_val").val()); // spit it out to the console
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="selected_val[]" value="" class="selected_val" />
<input type="radio" class="radio" name="radion_btn1" id="1" value="1" />1
<input type="radio" class="radio" name="radion_btn2" id="2" value="2" />2
<input type="radio" class="radio" name="radion_btn3" id="3" value="3" />3
You'll notice I added a common class for all radio buttons. This is what I'm attaching the event handler to. I also added the IDs to the radio button elements as well.
This may or may not work best for your scenario, but hopefully gets you started in the right direction.
Update
If you'd rather store the values in an array, just change it to an array:
let arr = [];
$(".radio").change(function() {
arr.push($(this).val());
$(".selected_val").val(JSON.stringify(arr));
}
Of course, that won't associate the ID with the value like with an object.

I need an array of selected checkboxes

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>

Tricky Javascript logic with Objects, Array and Booleans

I am having a lot of issue trying to figure out this logic. Let me set the stage here:
In the HTML there are some form/input elements type radio. Each of them have an ID assigned to it.
<form>
<input type="radio" name="oneAllowed" id="yesterday" />
<input type="radio" name="oneAllowed" id="today" />
<input type="radio" name="oneAllowed" id="tomorrow" />
</form>
Using Javascript essentially what I am trying to do is loop through the 3 objects, since they all have same name assigned within HTML only a single one can be selected, whichever one is returning true I want grab hold of that result then access the second key:value pair, for example for 'commitYesterday' it would be 'commitYesterday.hasValue();' and dispatch that to a different function for other calculation.
var urgentOrderSelector = function(){
var commitYesterday = {
isChecked: document.getElementById("yesterday").checked,
hasValue: function(){
if (this.isChecked == true) {
return 3;
};
};
};
var commitToday = {
isChecked: document.getElementById("today").checked,
hasValue: function(){
if (this.isChecked == true) {
return 2;
};
};
};
var commitTomorrow = {
isChecked: document.getElementById("tomorrow").checked,
hasValue: function(){
if (this.isChecked == true) {
return 1;
};
};
};
var urgentArray = [commitYesterday.isChecked, commitToday.isChecked, commitTomorrow.isChecked];
for(var i = 0; i <= urgentArray.length-1; i++){
if (urgentArray[i].isChecked == true) {
//This is where I am stuck. I was thinking of doing perhaps the following:
return urgentArray[i].hasValue();
};
}
};
Why don't you change your HTML to this:
<form>
<input type="radio" name="oneAllowed" id="yesterday" value="3" />
<input type="radio" name="oneAllowed" id="today" value="2" />
<input type="radio" name="oneAllowed" id="tomorrow" value="1" />
</form>
And use document.querySelector to get the selected elements:
document.querySelector('[type="radio"][name="oneAllowed"]:checked').value
If you actually need to run specific functions dependend on which radio box is checked you could add an attribute data-fn="fnName" to each input and then create an object with the keys as functions:
var fns = {'fnName1': function () {}, 'fnName2': function() {} …};
And then call the function defined by the Attribute:
fns[document.querySelector('[type="radio"][name="oneAllowed"]:checked').getAttribute('data-fn')]();
Not exactly sure what your end goal is.
But here's a more minified version of your logic. Hope it helps.
var urgentOrderSelector = function(){
var radioDict = {'yesterday':3, 'today':2, 'tomorrow':1};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')];
};
Alternatively, if you wanted to execute some function based on the selection, you could store the function pointers and execute them accordingly, ie:
var funcYesterday = function(){alert('yesterday');};
var funcToday = function(){alert('today');};
var funcTomorrow = function(){alert('tomorrow');};
var funcUrgentOrder = function(){
var radioDict = {
'yesterday' : funcYesterday,
'today' : funcToday,
'tomorrow' : funcTomorrow
};
return radioDict[$('input[name=oneAllowed]:checked').attr('id')]();
};
Or, much simpler, since you are using the 'value' property on your radios:
function urgentOrderSelector = function() {
return $('input[name=oneAllowed]:checked').val();
};

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.

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