How to loop over checked boxes and add to array - javascript

I am needing to loop over all of the checked check boxes of a specific name and add the values of that row to an array. My final array needs to look like this:
stmtData = {
sections: [
{ sectionCode: "AA", sectionName: "AA Test", amount: "33" },
{ sectionCode: "BB", sectionName: "BB Test", amount: "55" }
]
};
Looping over the checkboxes is the easy part:
var stmtData = [];
$.each($("input:checkbox[name='sectionElection']:checked"), function () {
// create sections array here
});
I'm getting the data like this, but there may be a better way?
stmtData["sectionCode"] = $(this).val();
stmtData["sectionName"] = $("#sectionElectionLbl_" + $(this).val()).text();
stmtData["amount"] = $("#sectionCost_" + $(this).val()).text();

You could improve it using map instead of each, bit rusty on jQuery but something like?
var stmtData = {}
stmtData.section = $("input:checkbox[name='sectionElection']:checked")
.map(function() {
var val = $(this).val();
var text = val.text();
return {
sectionCode: val,
sectionName = $("#sectionElectionLbl_" + text,
amount: text
}
});

Ok, I knew I had to use push somehow, figured it out and this works just fine.
var stmtData = [];
$.each($("input:checkbox[name='sectionElection']:checked"), function () {
// create sections array here
stmtData.push({
sectionCode: $(this).val(),
sectionName: $("#sectionElectionLbl_" + $(this).val()).text(),
amount: $("#sectionCost_" + $(this).val()).text()
});
});

Related

How to remove duplicate values from dynamic select in Javascript?

trying to figure this out with no such luck. Basically we populating a select with values from the service that it's being retrieved from. But there are duplicates in the select. Here's the code that's doing it. I'd like to remove the duplicates from what's getting returned that are in the "theProduct.name". I know this question has been asked before but I can't figure this out. The image attached is the select where it's happening. Thanks
function populateSearchProducts(data) {
var theData = data.data.results;
$field.empty().append('<option value=""> </option>');
for (var p in theData) {
var theProduct = theData[p];
$field.append('<option value="'+theProduct.id+'">'+theProduct.name+'</option>');
}
}
Try a filter to remove duplicates from the input data:
function populateSearchProducts(data) {
var theData = data.data.results.filter(function(item, pos, self) {
return self.indexOf(item) == pos;
});
$field.empty().append('<option value=""> </option>');
for (var p in theData) {
var theProduct = theData[p];
$field.append('<option value="'+theProduct.id+'">'+theProduct.name+'</option>');
}
}
function populateSearchProducts(data) {
data = data.data.results;
const dupes = new Set();
for(const {name, id} of Object.values(data)){
if(dupes.has(name)) continue;
$field.append(`<option value='${id}' > ${name} </option>`);
dupes.add(name);
}
}
You can keep track of the items already added to the DOM and then use a filter before adding new elements.
In the code below, the filter is looking at the id of each element to filter them out. If you want, you could use name (or any other attribute) to detect the duplicates and filter them out.
Something along the lines of:
var dataArray = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 3, name: 'three'},
{id: 4, name: 'four'},
{id: 2, name: 'two'}, // dupe
{id: 5, name: 'five'},
{id: 3, name: 'three'} // dupe
]
function populateSearchProducts(data, $field) {
//var theData = data.data.results;
var theData = data;
$field.empty().append('<option value=""> </option>');
// to keep track of the ones already in the drop-down
var alreadyAdded = [];
for (let p of theData) {
if(alreadyAdded.filter( item => item.id === p.id ).length <= 0 ){
$field.append('<option value="'+p.id+'">'+p.name+'</option>');
alreadyAdded.push(p);
}
}
}
// when docuemnt ready, populate the field
$(function(){
var field = $("#selOptions");
populateSearchProducts(dataArray, field);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selOptions" />
updated based on comments

How to get values in Json Array and use each of them separately

I have a JSON and I Want to separate each field of that in array part and then I want to use of each field separately and put them in separate array.
for example I have two part in my array and I want to divide the first part too room 1 and second part in room 2 .
I have to send Json to my second page with format room1 and room 2. and I do not know how can I do this
my json is like this right now :
"rooms": [
{
"adultcount": "1",
"childcount": "1,1"
},
{
"adultcount": "1",
"childcountandage": "0 "
}
]
but I want to change it like this :
"rooms": [
{
"rooms1": {
"adultcount": "1",
"childcount": "1,1"
}
},
{
"rooms2": {
"adultcount": "2",
"childcount": "10,1"
}
}
]
then I need to use them.
how can I do this with jquery ?
there is no need to change the json code I just wrote the sample the new json to define better.
here is my code :
$( document ).ready(function() {
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{ "adultcount":"1","childcountandage":"0 " }] }
var adultcount = research.rooms[0].adultcount;
var childcount = research.rooms[0].childcount;
});
Since you have an array that you want to make into an object and the property name seems to be the index inside the array, you can use a basic array.reduce:
var rooms = [
{ "adultcount":"1", "childcount":"1,1" },
{ "adultcount":"2", "childcount":"10,1" }
];
var roomsMap = rooms.reduce( function( map, room, index ) {
map[ 'room' + ( index + 1 ) ] = room;
return map;
}, {} );
var otherRoomsMap = rooms.map( function( room, index ) {
var wrapper = {};
wrapper[ 'room' + ( index + 1 ) ] = room;
return wrapper;
} );
console.log( roomsMap );
console.log( otherRoomsMap );
edit:
I have added the other example of keeping the array and just wrapping the objects isnide another object, but I have no idea what advantage that would give over the original array.
You can access your json array using loop
$.each(research, function (key, value) {
var adultcount = value.adultcount;
var childcount = value.childcount;
console.log("Adult count is:"+value.adultcount);
console.log("Child count is:"+value.childcount);
});
Try this:
var research={"rooms":[{ "adultcount":"1","childcount":"1,1" },{"adultcount":"1","childcountandage":"0 " }] };
var newResearch = {"rooms": []};
research.rooms.forEach(function(r) {
newResearch.rooms.push({"room1": r[0], "room2": r[1]});
});
console.log(newResearch);

Handsontable editing nested array

I am using handsontable and am having trouble getting the "beforeChange" and "afterChange" events to fire consistently, which I'm hoping use to commit updates to the database. I am using the following code (version 0.16.1):
HTML:
<div id="table"></div>
<div id="output"></div>
JavaScript:
var data = [{
id: 5,
name: 'Sedan',
price: 2000,
tags: ['pink', 'purple']
}, {
id: 6,
name: 'Truck',
price: 1500,
tags: ['green', 'blue']
}, {
id: 6,
name: 'SUV',
price: 1500,
tags: null
}];
var writeMessage = function(msg) {
var output = document.getElementById("output");
var div = document.createElement('DIV');
div.innerHTML = msg;
output.insertBefore(div, output.firstChild);
console.log(msg);
};
var tableDiv = document.getElementById("table");
this.table = new Handsontable(tableDiv, {
data: data,
colHeaders: ["id", "name", "price", "tags"],
columns: [{
data: "id"
}, {
data: "name"
}, {
data: "price"
}, {
data: "tags"
}],
beforeChange: function(changes, source) {
writeMessage("beforeChange: " + changes + ": " + source);
},
afterChange: function(changes, source) {
writeMessage("After Change fired: " + changes);
if (!changes) {
return;
}
var i, idx, key, newVal, modelID;
for (i = 0; i < changes.length; i++) {
idx = changes[i][0];
key = changes[i][1];
newVal = changes[i][3];
modelID = this.getDataAtRow(idx)[0];
writeMessage("New value: " + key + ": " + newVal);
}
}
});
http://codepen.io/anon/pen/GjzrdX?editors=0010
The event handlers fire when I'm editing the text and number fields and for the when tags are null, but do not fire for data objects with tag arrays (e.g. pink,purple; green,blue). How do I get the events to fire for the tag cells without modifying the data structure? Any advice would be greatly appreciated!
I believe that you are facing a bug here when trying to put an Array in a Cell but I cannot find anywhere in the handsontable documentation or any thread in their GitHub mentioning this issue... IMO, putting an Array in a Cell is suppose to be use as Source and not Data, which result in a cell that you can't edit (hence the events afterChange/beforeChange not triggered). In your example the third line is working because of the 'null' value which is not an Array.
Anyway, the only workaround I managed to do for you is to modify your data after you define your data structure (in order to respect your condition, but I strongly advice do modify them anyway because you will need to do that eventually).
Assuming that your tags can only contain two values :
var data1 = [];
for (var i=0; i<data.length;i++) {
if (data[i].tags != null) {
var temp = data[i].tags[0];
temp = temp.concat(',');
temp = temp.concat(data[i].tags[1]);
} else var temp = null;
data1.push({ id: data[i].id, name: data[i].name, price: data[i].price, tags: temp });
}
If the length of your Arrays tags can be more than that, just do a second loop to cover it.
See your code here with this solution implemented
You then can use data1 to load your table. If you need to save your data after modification, you can use a similar function to reverse it into your original data structure.

how to increase custom count in jquery json

If laptop model and serial id are same, i've to add new field totalModel and increase count. For example in below case: serialid "1" and laptop model "xyz" are coming two time so i want to add "totalModel" count as 2 and so on. How can i achieve this in jquery
This question is not really about jQuery, it is about mapping and filtering arrays and objects. However, we can use some jQuery convenience methods to solve it.
A large part of solving these problems is by properly defining what you want to do. It sounds from your question that you want to get a map of unique serial ids per laptop model type. We can use JavaScript's Array.prototype.reduce to produce just such a map (Note that we will take the 'sold' value for the first of each laptop model we encounter):
var laptop_models = data.reduce(function (memo, obj) {
if (!memo[obj.laptopModel]) {
memo[obj.laptopModel] = {
unique_serial_ids: [],
sold: obj.sold
};
}
if ($.inArray(obj.serialid, memo[obj.laptopModel].unique_serial_ids) === -1) {
memo[obj.laptopModel].unique_serial_ids.push(obj.serialid);
}
return memo;
}, {});
Next, we can map our laptop_models object into the array you specified as your expected result:
var result = $.map(laptop_models, function (laptop_model, model_name) {
return {
laptopModel: model_name,
totalModel: laptop_model.unique_serial_ids.length,
sold: laptop_model.sold
};
});
You got the idea already. Iterate through the array.
if them item is in a hash, increment the count, otherwise, add to the hash and set the count to 1
var hash = {};
for (var i = 0;i<data.length;i++) {
if (hash[data[i].laptopModel) {
hash[data[i].laptopModel]++;
}
else
hash[data[i].laptopModel] = 1;
}
var data = [
{
"serialid": 1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 5
},
{
"serialid" :1,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 4
},
{
"serialid": 1,
"laptopModel": "abc",
"sold": "yes",
"cnt": 3
},
{
"serialid": 3,
"laptopModel": "xyz",
"sold": "yes",
"cnt": 2
}];
var result = []; //work if result = {};
var tempArray = []; // used to store unique name to prevent complex loop
data.forEach(function(item){
if($.inArray(item.laptopModel, tempArray)< 0){// unique name
result.push(formatData(item));
tempArray.push(item.laptopModel);
}
else{
var indexNew = $.inArray(item.laptopModel, tempArray);
result[indexNew]["totalModel"] += 1;
}
});
function formatData(item){
return{
"laptopModel": item.laptopModel,
"sold": item.sold,
"totalModel": 1
}
}
alert(JSON.stringify(result)); //expect array 2 item but it's empty array
console.log(result); //Will have result 2 item when I view console window
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

getting and displaying a javascript object by index

var pdata = [{ Name: "Apples", Price: 1.99 },{ Name: "Bananas", Price: 2.45 }];
$('#add1').click(function () {
var selected = $('#produceList option:selected').index();
I have a variable set to an index and I want to get and display the javascript object by the var selected index
HTML
<div class-'item'></div>
JS
$('#add1').click(function () {
var selected = $('#produceList option:selected').index(),
item = pdata[selected];
$('.item').html(item.Name + ', ' + item.Price);
});
JSFIDDLE
If you have the index, you would just do
pdata[index];
so in your example
$('#add1').click(function () {
var index = $('#produceList option:selected').index();
var selected = pdata[index];
})
assuming the code you give in the question gives the index of the selected item.
The pairings are referenced using a simple array index, so your values are:
pdata[0] ---> {Name="Apples", Price=1.99}
pdata[1] ---> {Name="Bananas", Price=2.45}
To get to the specific attributes of the object, you need to use the name of the attribute, so your values are:
pdata[0].Name ---> "Apples"
pdata[0].Price ---> 1.99
pdata[1].Name ---> "Bananas"
pdata[1].Price ---> 2.45
So, to access the information that you want, you would use pdata[index].Name and pdata[index].Price, once you have retrieved the index.

Categories

Resources