concatenating strings in .each loop - javascript

This may be a dumb question but I can't seem to get it or find it anywhere.
I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).
Here is my code:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
console.log(data_str);
count++;
});
});
So that returns each data_str on a separate line but I need it to return it like this:
144:2~145:3~146:4~147:4~148:5 (so on)
Any help would be appreciated, thanks!

Use map and join :
jQuery('#updateAllContentButton').click(function() {
console.log(jQuery('.CommentaryItem').map(function(i) {
return GetID(jQuery(this)) + ':' + (i+1);
}).get().join('~'));
});
Note that you don't have to count yourself : Most jQuery iteration functions do it for you.

You can use an array for that. Like this...
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var arr = [];
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');
arr.push(data_str);
//console.log(data_str);
count++;
});
console.log(arr.join());
});

try this:
jQuery('#updateAllContentButton').click(function() {
var count = 1;
var data_str = "";
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});

change
var data_str = (id + ':' + count + '~');
to
data_str+ = (id + ':' + count + '~');
full code
jQuery('#updateAllContentButton').click(function() {
var count = 1,
data_str;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
data_str += (id + ':' + count + '~');
console.log(data_str);
count++;
});
});

Related

Insert "and" before the last element jquery

var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
'&nbsp' + ':' + '&#160' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + '&nbsp' + ':' + '&#160' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!

JavaScript for loop not working?

I haven't really used loops before and I can't seem to figure out why my code isn't working. Was hoping for someone to help point me in the right direction.
return firebase.database().ref('Users/' + uid + "/PDR").once('value').then(function display(dataSnapshot) {
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++) {
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>' + num + '</td><td>' + dateFrom + '</td><td>' + dateTo + '</td><td>' + dbActivity + '</td></tr>'
})
}
})
Im trying to pull data from my Firebase backend and display it in a table, currently it only runs once.
Thanks for any help and advice!
Not sure what is going on in the dataSnapshot object, but first step in javascript debugging, is to add alert("Here"); in your code to see what (if anything) is being returned
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++){
alert("Here " + i); //Show me the loop variable
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
alert(num);
alert(dateFrom );
alert(dateTo );
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>'+ num +'</td><td>'+ dateFrom + '</td><td>'+ dateTo +'</td><td>'+ dbActivity +'</td></tr>'

jQuery use dynamically created ID

I am trying to use dynamically created IDs in javascript function, but it's not working. I thought that prepending # to string id should work, but it's not.
Code:
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("'#" + idCheckBoxToCompare + "'").prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("'#" + textBoxID + "'").val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("'#" + idInputBox + "'").val();
if ($("'#" + idCheckBox + "'").prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("'#" + idCheckBox + "'").prop('checked', false);
}
}
}
}
}
I've tried to build same id as this is:
'#testid'
so usage would be:
$('#testid')
But it's not working. How to use properly dynamically created IDs?
Your code is look complicated with too many " and '. Also Javascript can concat string and number by just use +. No need to convert it to string first. So, I updated it to make it more readable.
Try this
var IterateCheckedDatesAndUncheckWithSameValue = function(elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber;
if ($('#' + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber;
textBoxValue = $('#' + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i;
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i;
inputBoxValue = $('#' + idInputBox).val();
if ($('#' + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$('#' + idCheckBox).prop('checked', false);
}
}
console.log('#' + idCheckBox); //print here just to see the id results
}
}
}
ID in html can be only one element per page. So please make sure that the ID you generate from this method not match with other.
Jquery selector can read String variable.
So you can just do var id = "#test". Then put it like this $(id).
Or
var id = "test"; then $("#"+test).
Use this,
var IterateCheckedDatesAndUncheckWithSameValue = function (elementNumber) {
idCheckBoxToCompare = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + elementNumber.toString();
if ($("#" + idCheckBoxToCompare).prop('checked') === false) {
return;
}
textBoxID = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + elementNumber.toString();
textBoxValue = $("#" + textBoxID).val();
for (i = 1; i < 8; i++) {
if (i !== elementNumber) {
idCheckBox = "CMP_KD1_tcDE_tctpDNDR_chkDNDRDay" + i.toString();
idInputBox = "CMP_KD1_tcDE_tctpDNDR_txtDNDRDay" + i.toString();
inputBoxValue = $("#" + idInputBox).val();
if ($("#" + idCheckBox).prop('checked') === true) {
if (inputBoxValue === textBoxValue) {
$("#" + idCheckBox).prop('checked', false);
}
}
}
}
}
I face the same problem using Jquery .Try $(document).getElementbyId('myid'). Hope help.
Edit
Change :
$("#" + idCheckBoxToCompare) by $(document).getElementbyId(idCheckBoxToCompare)

Counting in jquery Array

I seem to have trouble calculating some numbers together. When I want to use:
for (var key in week_total) {
$("." + key).html(week_total[key]);
}
I am getting a NaN and thereforce every group has a NaN. Is this the right way of even using week_total[group] = week_total[group] + work_minutes;?
My script:
drawCallback: function (settings) {
var api = this.api(), data;
var rows = api.rows({page: 'current'}).nodes();
var last = null;
var week_total = new Array;
api.column(weekColumn, { page: 'current' }).data().each(function (group, i) {
var work_hours = api.column(hourColumn).data()[i].split(':');
var work_minutes = (+ work_hours[0]) * 60 + (+ work_hours[1]);
week_total[group] = week_total[group] + work_minutes;
if (last !== group) {
$(rows).eq(i).before('<tr><td colspan="5">{{ trans('admin.worktime.field.week') }} ' + group + '</td><td colspan="3" style="font-style:italic;" class="' + group + '"></td></tr>');
last = group;
}
});
for (var key in week_total) {
$("." + key).html(week_total[key]);
}
var array = {
work_month: work_month,
work_year: work_year
};
history.pushState(null, null, '?' + $.param(array));
drawDataTable(this);
}
I think, problem is in not initialized week_total array.
Calculating should be like
week_total[group] = week_total[group]
? week_total[group] + work_minutes
: work_minutes;
If week_total[group] is undefined then week_total[group] + 1 will be NaN

For loop inside object javascript

I'm using lightGallery and I'm using dynamic creation of galleries, this is the code to generate just one image:
$(this).lightGallery({
dynamic:true,
dynamicEl: [{
'src':'css/images/pictures/gal_'+id+'/1.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/1.jpg'
}]
});
This id variable is always the same, but I want to loop through a number which I take for example from variable x. So, if x=4 the code generated would look like this:
$(this).lightGallery({
dynamic:true,
dynamicEl: [{
'src':'css/images/pictures/gal_'+id+'/1.jpg', //here's 1
'thumb':'css/images/thumbnails/gal_'+id+'/1.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/2.jpg', //here's 2 and so on
'thumb':'css/images/thumbnails/gal_'+id+'/2.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/3.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/3.jpg'
},{
'src':'css/images/pictures/gal_'+id+'/4.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/4.jpg'
}]
});
So I guess the question is how to include a for loop inside an object, if that's even possible, thanks in advance!
No. It's not possible to have control structures(like loops) inside an object definition. You need to create your array of images first, like this:
var dynamicEl = [];
for (var i = 1; i <= 4; i++) {
dynamicEl.push({
'src':'css/images/pictures/gal_' + id + '/'+ i + '.jpg',
'thumb':'css/images/thumbnails/gal_' + id + '/' + i + '.jpg'
});
}
And then to pass it onto the object definition:
$(this).lightGallery({
dynamic:true,
dynamicEl: dynamicEl
});
first create a method to dynamically generate thumbs
function genThumbs(count, id)
{
var arr = [];
for ( var counter = 1; counter <= count; counter++)
{
arr.push( {
'src':'css/images/pictures/gal_'+id+'/' + counter + '.jpg',
'thumb':'css/images/thumbnails/gal_'+id+'/' + counter + '.jpg'
} );
}
return arr;
}
then use the same while calling the gallery
$(this).lightGallery({
dynamic:true,
dynamicEl: genThumbs(5, id)
});
Try this
var genEls = function(id, count)
{
var els = [];
for(i = 1; i <= count; i++)
{
els.push({
'src':'css/images/pictures/gal_'+ id + '/' + i + '.jpg',
'thumb':'css/images/thumbnails/gal_' + id + '/' + i + '.jpg',
});
}
return els;
}
var id = 3;
var count = 4;
$(this).lightGallery({
dynamic:true,
dynamicEl: genEls(id,count);
});
This is as inline as it can get ;)
Hope this helps ...

Categories

Resources