Iterate through Id's, store values, put into an array - javascript

I want to be able to iterate through a number of ids called "#option1", "#option2" etc. The problem is its for an interactive form and I don't know how many options there will be. So I need a way to iterate through the amount in the DOM when the user clicks ("#dothis").
Then I need to get the values of the those options, put into an array called arraylist.
$("#doThis").on("click", function() {
var optionone = $("#option1").val();
var optiontwo = $("#option2").val();
var optionthree = $("#option3").val();
var optionfour = $("#option4").val();
var optionfive = $("#option5").val();
var arrayList = [optionone, optiontwo, optionthree,
optionfour, optionfive];
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

As Andy said, give every option the same class. In my example it's "option-item".
$("#doThis").on("click", function() {
var arrayList = [];
$('.option-item').each(function(i) {
arrayList[i] = $(this).val();
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
});
Every value is now stored in the array.
see fiddle.
greetings timmi

With your code as is, you can use a selector that selects everything with an ID that starts with 'option', like so [id^="option"], here's how to use it:
$("#doThis").on("click", function () {
var arrayList = [];
$('[id^="option"]').each(function (index, element) {
arrayList.push($(element).val() );
});
var decide = arrayList[Math.floor(Math.random() *
arrayList.length)];
$("#verdict").text(decide);
}); // end of dothis click event

Related

Create JSON with multiple values

I need to create a JSON with data every time I click on a button BTN. Here is how I create my JSON :
$(document).ready(function () {
var maj = {};
$("#btnSubmitRejetRefModele").click(function() {
maj['one'] = 'a'
maj['two'] = 'b'
maj['three'] = 'c'
}
Values a,b,c are changing every time and I want to store each value in a JSON with the structure :
maj = {
"0" : {'one':'a','two':'b','three':'b'} ,
"1" : {'one':'a2','two':'b2','three':'c2},
// ...
}
How can I code and append my data in my JSON each time I click on the button. This JSON will be used in a post method to insert values into PGsql
You need to check the size of the current object, and insert the data to the position of that size:
$(document).ready(function() {
var maj = {};
$("#btnSubmitRejetRefModele").click(function() {
var size = Object.keys(maj).length;
var data = {
one: 'a' + (size+1),
two: 'b' + (size+1),
three: 'c' + (size+1)
}
maj[size] = data;
console.clear();
console.log(maj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmitRejetRefModele">Add</button>
If you need an alternative, here's my original answer, which is using an array of objects, you can use it later as maj[0], maj[1], and so on:
$(document).ready(function() {
var maj = [];
$("#btnSubmitRejetRefModele").click(function() {
var data = {
one: 'a',
two: 'b',
three: 'c'
}
maj.push(data);
console.clear();
console.log(maj);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnSubmitRejetRefModele">Add</button>
This is not exactly the format you need, but maybe helps.
An alternative could be storing it in an array.
let data = {
myArray: [{'one':'a','two':'b','three':'b'}]
}
Then every time you can just add data by adding to that array.
data.myArray.push({'one':'a2','two':'b2','three':'b2'})
Advantage, no need to keep track of any counter variables.
Disadvantage, removing things from the array might be less performant or less convenient. But that depends on the use case.
Readability is the most important thing when writing code you want to maintain.
You should keep track of button clicks count, and use it when creating the new part of your JSON object.
var maj = {};
var counter = 0;
$("#btnSubmitRejetRefModele").click(function() {
var temp = {}
temp['one'] = aNewValue
temp['two'] = bNewValue
temp['three'] = cNewValue
maj[counter++] = temp
}
but finally, I recommend you to use an array instead of an object(it's already indexed)
just push your new created objects in it and whenever you wanted to convert it to an object, do this:
myObject = Object.assign({}, maj);

remove items from array with the same id one by one

the problem is that I have multiple objects with the same id. As you can see this works when it comes to removing all the items with the same id. How I can remove the objects one by one no matter if they are the same ID...thanks
individualObjects:[],
actions:{
increment:function(){
var obj = this.get('object');
this.get('individualObjects').pushObject(obj);
},
decrement:function(){
var obj = this.get('object');
var filter = this.get('individualObjects').findBy('obj_id', obj.get('obj_id'));
this.get('individualObjects').removeObject(filter);
}
}
Well to filter array you would need to use Array.filter to find out the items that do not belong in the "individualObjects" and later simply remove them by using "removeObjects"
decrement:function(){
var objects = this.get('individualObjects')
var notWanted = objects.filterBy('obj_id', this.get('object.obj_id'));
this.get('individualObjects').removeObjects(notWanted);
}
and solution 2
decrement:function(){
var removeObj = this.get('object');
var objects = this.get('individualObjects')
// As the condition is true given object is returned
var notWanted = objects.filter(obj => { return obj.get('obj_id') === removeObj.get('obj_id')  });
this.get('individualObjects').removeObjects(notWanted);
}
Ok so you want to remove items one by one. Weird but can be accomplished
first get the length for
var notWantedCount = objects.filterBy('obj_id', this.get('object.obj_id')).length;
Now
for(var i=0; i <= notWantedCount; i++) {
var toRemove = individualObjects.findBy('obj_id', obj.get('obj_id'));
individualObjects.removeObject(toRemove);
// Make some custom actions one by one.
}
I don't know ember, but you'll want to do a foreach on the array, and then test for id on each one. It should be something like this:
decrement:function(){
var obj = this.get('object');
self = this;
this.get('individualObjects').each(function(individualObject) {
if (individualObject.get('obj_id') == obj.get('obj_id'))
... you want to do something here? ...
self.get('individualObjects').removeObject(individualObject);
}
}
That way you can remove each object individually. Running any necessary code before or after it's removed. If you want to sort it first, you can do that before running the each function.

I want to insert values dynamically to hash map

var markerList1={};
var markerList=[];
and adding iterator values from the one for loop
function addSomething() // this function will multiple times from a for loop
{
image ='../css/abc/'+image[iterator]+'.png';
var data = respData[iterator];
var box = getbox(data);
var markerOpts = {
position : coordinates[iterator],
map : map,
icon :image,
title :data[1],
id : data[11]
};
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);
markerList1[markerOpts.title].push(vmarks);
}
whenever we call the function i want append the array's values to same index
markerList1[data[11]].push(vmarks);
but i'm not getting above result, when i markerList1[data[11]) then i'm getting only the last value i.e thirdvmark
i want output like this= markerList1[data[11]] = {firstvmark, secondvmark, thirdvmark};
You cannot do push to an object markerList1, only to an array.
change this
markerList1[markerOpts.title].push(vmarks);`
To this
markerList1[markerOpts.title] = vmarks;
markerList1[data[11]] is never initialized before you push something inside.
You can initialize it only once with a simple test:
if (! (data[11] in markerList1) ) {
markerList1[data[11]] = [];
}
markerList1[data[11]].push(vmarks);
Or in a shorter and safer way:
markerList1[data[11]] = markerList1[data[11]] || [];
markerList1[data[11]].push(vmarks);
(And please put data[11] in a variable)
Try this-
var vmarks = new google.maps.Marker(markerOpts);
markerList.push(vmarks);//you already pushing vmarks to array
markerList1[markerOpts.title]=markerList;//assign array to your markerList1 map

Find Index of Column(s) after it has been Moved

We are using DHTMLX Grid. Need some help, please.
I have a table and each columns (has filter/dropdown) are allocated an id eg. fac, date, sel, loc, tag ... etc
We have hard coded the index of columns to set and get the cookie elsewhere.
function doInitGrid(){
mygrid.setColumnIds("fac,date,sel,loc,tag"); //set ids
mygrid.attachEvent("onFilterStart",function(ind,data)
{
setCookie("Tray_fac_filter",mygrid.getFilterElement(0).value,365); //column index 0
setCookie("Tray_loc_filter",mygrid.getFilterElement(3).value,365);//column index 3
setCookie("Tray_tag_filter",mygrid.getFilterElement(4).value,365); //column index 4
mygrid.getFilterElement(0).value = getCookie("Tray_fac_filter")
mygrid.getFilterElement(3).value = getCookie("Tray_dep_filter")
mygrid.getFilterElement(4).value = getCookie("Tray_prg_filter")
});
}
But when the columns are moved, the problem arises as the index of the column changes yet it is set in setCookie /getCoookie
DHTMLX allows to get the index of the id using --
var colInd = grid.getColIndexById(id);
eg: var colInd = grid.getColIndexById(date); // outputs 1.
After moving the date column to the end -- fac, sel, loc, tag, date // it will output 4.
However, we have about 14 columns that can be moved/rearranged and I could use the
var colInd = grid.getColIndexById(id); 15 times
var facInd = grid.getColIndexById("fac");
var dateInd = grid.getColIndexById("date");
var selInd = grid.getColIndexById("sel");
var locInd = grid.getColIndexById("loc";
var tagInd = grid.getColIndexById("tag");
and put those variables in the set/get cookie. I was thinking if there was a better way.
To understand the code better, I have put the minimised version of the code in fiddle.
http://jsfiddle.net/19eggs/s5myW/2/
You've got the best answer I think. Do it in a loop and it's easier:
var cookie_prefix = "Fray_filter_";
var cookie_dur = 365;
var num_cols = dhx_grid.getColumnCount();
// filter vals to cookies
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var filter = mygrid.getFilterElement(col_idx)
if (filter) { // not all columns may have a filter
var col_id = dhx_grid.getColumnId(col_idx);
var cookie_name = cookie_prefix+col_id;
setCookie(cookie_name, filter.value, cookie_dur);
}
}
// cookies to filter vals
for (var col_idx=0; col_idx<num_cols; col_idx++) {
var col_id = dhx_grid.getColumnId(col_idx);
var filter_val = getCookie(cookie_prefix+col_id);
var filter = mygrid.getFilterElement(col_idx)
filter.value = filter_val;
}
You can use dhtmlxgrid native event to assign the correct id everytime a column is moved.
The event is called onAfterCMove, you can check the documentation here. onAfterCMove Event
You would do something like:
mygrid.attachEvent('onAfterCMove',function(cInd,posInd){
//Your processing here to change the cookies; where cInd is the index of the column moved
//and posInd, is the position where it Was moved
}):

Loop through tr's with Jquery and compare contents with next row in series

I'm somewhat new to jQuery/javascript, and would like to compare the contents of row[i] in a table body with row[i+1].
Is this something I can do with jQuery or should I just use plain old JS and getElementByid and then loop that way? using the .each doesn't appear to give anyway of accessing the next element in the series easily.
I assume if/when I find a solution to this, I then need to figure out how to compare row[i].td[j] to row[i+1].td[j].
I imagine this is simple, but my searches so far have come up with null.
note that next may end up being an empty jquery object if you're at the last tr
var trs = $('tr');
trs.each(function(i,n) {
var current = $(n);
var next = trs.eq(i+1);
});
You could store the previous element and do the compare on the 'next':
var callback = (function() {
var lastTr;
return (function(i, n) {
if (lastTr) {
//logic $(this) is 'next', lastTr is 'current'
}
lastTr = $(this);
});
})();;
$(document).ready(function() {
$('tr').each(callback);
});
my full solution so far involves something along these lines:
function myfunc(table) {
$(table).each(function(i,n) {
var current = $(n);
var next = $(table).eq(i+1);
if (next.length) {
current.children().each(function(a,b) {
var current_td = $.trim($(b).text());
var next_td = $.trim(next.children().eq(a).text());
/* compare here */
});
}
});
}

Categories

Resources