Adding checkbox selected values in multi-dimensional array - javascript

I am working on this demo. How can I add each selected row as an array into the data [] so that it looks like this:
[{"Cell phone":"BlackBerry Bold 9650","Rating":"2/5","Location":"UK"},
{"Cell phone":" Samsung Galaxy","Rating":"3/5","Location":"US"}]
Here is the code I have:
var data = [];
function myfunc(ele) {
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});

check if this works,
here is the fiddle demo
var data = [];
function myfunc(ele) {
var values = [];
var keys = [];
$.each($("input[name='case[]']:checked").closest("table").find('th'),
function () {
keys.push($(this).text());
});
keys.shift(); // to remove the first key
var len = keys.length, obj={}, ctr=0;
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
obj[keys[ctr]]=$(this).text();
ctr++;
if(ctr==len){
values.push(obj);
obj={};
ctr=0;
}
});
alert("val---" + JSON.stringify(values));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});

http://jsfiddle.net/ugdas2em/
Try this:
var data = {};
function myfunc(ele) {
//var values = new Array();
var k = 0;
var j = 0;
data[k] = {};
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
if(j==3)
{
k = k+1;
data[k] = {};
j = 0;
}
//values.push($(this).text());
data[k][j] = $(this).text();
j=j+1;
});
console.debug(data);
//alert("val---" + values.join (", "));
}
$(document).ready(function() {
$("input.case").click(myfunc);
});
Note: If you want then you can use [] with data variable in place of {} in my code. You need to replace at three place. Thanks.

Related

Instantiate the value of an array from one function to a different function in jquery

I want to get the result of a jquery function attached to an id and change e.g
<script>
$('#dateID').change(function(){
var bookday = $(this).val();
$.post('getDates.php',{postbookday:bookday},
function(data){
var array = JSON.parse("[" + data + "]");
var list = [];
var newArray = array.flat([2]);
for (var i = 0; i < newArray.length; i++) {
list.push(newArray[i]);
};
if (list.length>96) {
alert("Sorry, day fully booked!");
}
else{
function selectedTime(list) {
return [a, b, c];
}
var result = selectedTime(list);
var myArray = [];
for (var i=0; i < result[2].length; i++) {
if (result[2][i] === '09:00') {
myArray.push(['09:00','10:00']);
}
if (result[2][i] === '10:00') {
myArray.push(['10:00','11:00']);
// here is myArray
}
}
}
});
});
</script>
and then use it as the input in another different function below:
$('#disableTimeRangesExample').timepicker(
{
'disableTimeRanges': myArray
}
);
How do I get myArray in the next function? considering that it is not static.
You have two options:
1. save the variable in outer scope:
var myArray;
$('#selectedDate').change(function(
...some computations...
myArray = [['1pm', '2pm']];
});
$('#disableTimeRangesExample').timepicker({
'disableTimeRanges': myArray
});
2. save in jQuery data
$('#selectedDate').change(function(
...some computations...
$(this).data('array', [['1pm', '2pm']]);
});
$('#disableTimeRangesExample').timepicker({
'disableTimeRanges': $('#selectedDate').data('array') || []
});
As a side note you will probably also need to update timepicker on each change.
EDIT: to update time picker on change of the input you need to put this inside change event:
$('#dateID').change(function(){
var bookday = $(this).val();
$.post('getDates.php',{postbookday:bookday},
function(data){
var array = JSON.parse("[" + data + "]");
var list = [];
var newArray = array.flat([2]);
for (var i = 0; i < newArray.length; i++) {
list.push(newArray[i]);
};
if (list.length>96) {
alert("Sorry, day fully booked!");
}
else{
function selectedTime(list) {
return [a, b, c];
}
var result = selectedTime(list);
var myArray = [];
for (var i=0; i < result[2].length; i++) {
if (result[2][i] === '09:00') {
myArray.push(['09:00','10:00']);
}
if (result[2][i] === '10:00') {
myArray.push(['10:00','11:00']);
// here is myArray
}
}
$('#disableTimeRangesExample').timepicker(
'option', {'disableTimeRanges': myArray}
);
}
});
});
$('#disableTimeRangesExample').timepicker();

Error : Uncaught TypeError: Cannot read property 'value' of undefined

var myData = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';
$(document).ready(function () {
var myData = new Array();
for (i in myData) {
var item = myData[i];
var key = item[0];
var value = [item[1], item[2]];
var index = getElementindex(key);
if (index != -1) {
var element = finalArr[index];
element.value.push(value);
} else {
var newArr = new Array();
var element = {
key: "",
value: ""
};
element.key = key;
newArr.push(value);
element.value = newArr;
finalArr.push(element);
}
}
function getElementindex(key) {
for (i in finalArr) {
if (finalArr[i].key == key) return -i;
}
console.log(JSON.stringify(finalArr));
}
});
The value of myData string is overwritten when
var myData = new Array();
To convert the string into JSON object, use
myData = JSON.parse(myData);
<script>
var mstdta=[['A',453627726262,10],['A',453627726262,5],['B',453627726262,10],['B',453627726262,0],['C',453627726262,10],['C',453627726262,70]];
$(document).ready(function() {
var myArray = new Array();
for(i in mstdta){
var item=mstdta[i];
var key=item[0];
var value=[item[1],item[2]];
var index=getElementIndex(key);
if(index!=-1){
var element=myArray[index];
element.value.push(value);
}else{
var newArr=new Array();
var element={key:"",value:""};
element.key=key;
newArr.push(value);
element.value=newArr;
myArray.push(element);
}
}
function getElementIndex(key){
for(j in myArray){
if(myArray[j].key==key)
return j;
}
return -1;
}
console.log(JSON.stringify(myArray));
});
</script>
try this, eval() parse the string as actual array in JS
$(document).ready(function() {
var myData = new Array();
myDataString = '[["absa",1447842600000,1492],["amer",1447842600000,8698],["apac",1447842600000,8361],["emea",1447842540000,70406],["odc",1447842660000,0]]';
myData = eval(myDataString);
// code goes here

Angular ngGrid data presentation

I'm new to Angular and my experience with Javascript is not very extensive. I am failing to show data in ngGrid using following code. What is the problem?
In essence. I am loading data from a web-service, performing a transform (pivot) on it and then I want to present it in a grid.
Please see the following
app.js -> starting poing
var konstruktApp= angular.module('konstruktApp',['ngGrid']);
dataService.js -> web service call
'use strict';
konstruktApp.service('DataService',function DataService($http){
var callHttp = function(){
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get("http://83.250.197.214/konstrukt.service/Konstrukt.SL.DummyBudgetService.svc/GetDummyBudgetData/");
};
return {
getDummyData: callHttp
};
});
ngGridController.js -> where the logic resides...
$scope.getData = DataService.getDummyData;
$scope.gridOptions = {data:'result'};
var getData = function() {
$scope.getData().then(function (response) {
var res = pivotData(response.data);
$scope.result = res.data.PivotedRows;
$scope.columns = res.cols;
console.log('from the success handler at ' + new Date());
}, function (reason) {
console.log('failed: ');
console.log(reason);
});
};
..and here is the logic that "pivots" the data
var pivotData = function(data) {
var firstColumn = "Dim1";
var secondColumn = "Period";
var columns = [];
columns.push({
field: firstColumn,
enableCellEdit: false
});
var pivotedArray = {};
pivotedArray.PivotedRows = [];
var rowItems = [];
var rowArray = {};
var previusFirstColumnValue = -1;
var firstColumnValue = 1;
//for each row
for (var i = 0; i < data.Rows.length; i = i + 1) {
//firstColumnValue = $scope.dataCollection.Rows[i].FindCell.Cells[firstColumn].Value;
firstColumnValue = findCell(data.Rows[i].Cells, firstColumn).Value;
//var secondColumnValue = data.Rows[i].Cells[secondColumn].Value;
var secondColumnValue = findCell(data.Rows[i].Cells, secondColumn).Value;
//if first column value has changed, add new row
if (firstColumnValue != previusFirstColumnValue) {
if (i !== 0) {
for (var j = 0; j < rowItems.length; j = j + 1) {
rowArray[rowItems[j].name] = rowItems[j].value;
}
pivotedArray.PivotedRows.push( rowArray);
rowArray = {};
rowItems = [];
}
rowItems.push({
name: firstColumn,
//value: $scope.dataCollection.Rows[i].Cells[firstColumn].Value
value: findCell(data.Rows[i].Cells, firstColumn).Value
});
}
//if (columns.indexOf({field: secondColumnValue}) == -1) {
if (i < 12) {
columns.push({
field: secondColumnValue,
editableCellTemplate: "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-blur=\"lostFocus()\" ng-model=\"COL_FIELD\" ng-change=\"dataChanged(col,row,row.entity)\"/>",
enableCellEdit: true
});
}
rowItems.push({
name: secondColumnValue,
value: findCell(data.Rows[i].Cells, secondColumn).Value
});
previusFirstColumnValue = firstColumnValue;
}
for (var k = 0; k < rowItems.length; k = k + 1) {
rowArray[rowItems[k].name] = rowItems[k].value;
}
// $scope.columns = columns;
pivotedArray.PivotedRows.push( rowArray);
return {data: pivotedArray, cols: columns};
};
plnkr: http://plnkr.co/edit/ZqC7696xGbUtuWGIvnYs?p=preview
EDIT: The data correlation rows<-> columns is correct, I suspect there is something wrong with data in the pivotedArray.PivotedRows array.
It turned out that moving the code to a new plnkr made the difference. Now, thats a few hours of my life that I want back :)

generate list of variables from a FOR loop

var select = [];
for (var i = 0; i < nameslots; i += 1) {
select[i] = this.value;
}
This is an extract of my code. I want to generate a list of variables (select1, select2, etc. depending on the length of nameslots in the for.
This doesn't seem to be working. How can I achieve this? If you require the full code I can post it.
EDIT: full code for this specific function.
//name and time slots
function gennametime() {
document.getElementById('slots').innerHTML = '';
var namelist = editnamebox.children, slotnameHtml = '', optionlist;
nameslots = document.getElementById('setpresentslots').value;
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<option>'
+ namelist[f].children[0].value
+ '</option>';
};
var select = [];
for (var i = 0; i < nameslots; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.id = 'personname' + i;
slottime.id = 'persontime' + i;
slottime.className = 'persontime';
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option><option value="3">00:03</option><option value="4">00:04</option><option value="5">00:05</option><option value="6">00:06</option><option value="7">00:07</option><option value="8">00:08</option><option value="9">00:09</option><option value="10">00:10</option><option value="15">00:15</option><option value="20">00:20</option><option value="25">00:25</option><option value="30">00:30</option><option value="35">00:35</option><option value="40">00:40</option><option value="45">00:45</option><option value="50">00:50</option><option value="55">00:55</option><option value="60">1:00</option><option value="75">1:15</option><option value="90">1:30</option><option value="105">1:45</option><option value="120">2:00</option></optgroup>';
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
(function (slottime) {
slottime.addEventListener("change", function () {
select[i] = this.value;
});
})(slottime);
}
}
You'll have to close in the iterator as well in that IIFE
(function (slottime, j) {
slottime.addEventListener("change", function () {
select[j] = this.value;
});
})(slottime, i);
and it's only updated when the element actually change
The cool thing about JavaScript arrays is that you can add things to them after the fact.
var select = [];
for(var i = 0; i < nameSlots; i++) {
var newValue = this.value;
// Push appends the new value to the end of the array.
select.push(newValue);
}

Get anchor tag values in jQuery

I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});

Categories