Bind multiple javascript variables to one function () => { - javascript

I want to rewrite the first line of this code blah_1.bind(() => { to combine 1, 2 and 3 to eliminate the need to duplicate lines after the first. Is there a way to add commas and have all the .bind on one line like blah_1,blah_2,blah_3.bind( ?
blah_1.bind(() => {
if(blah_1.get().length > 0){
$('body').css({'blah' : 'blah' + blah_1.get() + blah_2.get() + blah_3.get()});
}else{
$('body').css({'blah' : blah_1.get()});
}
});
blah_2.bind(() => {
if(blah_1.get().length > 0){
$('body').css({'blah' : 'blah' + blah_1.get() + blah_2.get() + blah_3.get()});
}else{
$('body').css({'blah' : blah_1.get()});
}
});
blah_3.bind(() => {
if(blah_1.get().length > 0){
$('body').css({'blah' : 'blah' + blah_1.get() + blah_2.get() + blah_3.get()});
}else{
$('body').css({'blah' : blah_1.get()});
}
});

Related

Nightwatch count number of element

I'am a newbie with Nightwatch and i would like to count the number of element. I am able to do this but I don't understand how the variable is interpreted, here my code :
browser.elements('xpath', '/html/body/div[1]/div[3]/div[2]/div/div[1]/div/div[3]/table/tbody/tr/td[2]', function (elements) {
var nb = 0
elements.value.forEach(function (elementsObj, index) {
browser.elementIdText(elementsObj.ELEMENT, function (result) {
if (result.value != "") {
nb = nb + 1
console.log(result.value)
}
//console.log("There are : " + nb)
})
//console.log("There are : " + nb)
})
This display all elements I want. The output is :
Element 1
Element 2
and so on...
Now, I would like to have this :
There are X elements :
Element 1
Element 2
And so on...
But I try to print my variable "nb" but it doesn't work... How can I store and display my "nb" variable ?
Thanks,
My guess is that those commented console.log when not commented are executed before your loop ends... and therefore they are most likely returning :
"There are : 0"
Have you tried to "await" for the forEach loop to end?
Maybe something like:
browser.elements('xpath', '/html/body/div[1]/div[3]/div[2]/div/div[1]/div/div[3]/table/tbody/tr/td[2]', function (elements) {
var nb = 0
elements.value.forEach(async function (elementsObj, index) {
await browser.elementIdText(elementsObj.ELEMENT, function (result) {
if (result.value != "") {
nb = nb + 1
console.log(result.value)
}
//console.log("There are : " + nb)
})
console.log("There are : " + nb)
})
You can store the values in an array. And then parse the length after the forEach loop is completed. something like this:
browser.elements('xpath', '/html/body/div[1]/div[3]/div[2]/div/div[1]/div/div[3]/table/tbody/tr/td[2]', function (elements) {
var nb = []
elements.value.forEach(function (elementsObj, index) {
browser.elementIdText(elementsObj.ELEMENT, function (result) {
if (result.value != "") {
console.log(result.value)
nb.push(result.value)
}
})
})
console.log('There are ' + nb.length() + 'elements')
for (const nbItem of nb) {
console.log(nbItem)
}
})

Javascript - how to write every % 2 === 0 in 1st column else 2cnd column

I have a json file. I would like to write the content from it into two divs. If json.length % 2 === 0 then write in <div id="data1"> else write it in <div id="data2">.
I recieve the json file, but it only writes the 1st if sentence.
I hope the code will make more sense then I do =)
var data1 = document.getElementById("data1");
var data2 = document.getElementById("data2");
loadJSON(function(json) {
var l = Object.keys(json).length;
console.log("json start");
for (var i = 0; i <= l; i++){
console.log(i);
if (l % 2 === 0){
for (x in json) {
data1.innerHTML="<img src=" + json[x].picture + "/>";
data1.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
console.log("0 " + l); // this never prints
}
} else {
for (x in json) {
data2.innerHTML="<img src=" + json[x].picture + "/>";
data2.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
console.log("1 " + l); // this never prints
}
}
}
});
Edit 1:
So, I've changed l % 2 === 0 to i % 2 === 0 and added innerHTML += and things kind of work now. The problem now, is that I get everything two times. So basically I get the same picture and the price in both divs...
Any idea how I could solve this?
In your code you apppear to have made a typo.
When iterating over an array, your should use the index variable in this case.
Therefore the fix should be:
if (i % 2 === 0){
...
}
Instead of:
if (l % 2 === 0){
...
}
As an answer to your secondary problem:
You are looping through your json results twice.
Just reorder your code a little bit.
The result would be something like this:
loadJSON(function(json) {
console.log("json start");
var i = 0;
for (x in json){
console.log(i);
if (i % 2 === 0){
data1.innerHTML="<img src=" + json[x].picture + "/>";
data1.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
console.log("0 " + l); // this never prints
} else {
data2.innerHTML="<img src=" + json[x].picture + "/>";
data2.innerHTML+=json[x].price_thingy.price + json[x].price_thingy.suf;
console.log("1 " + l); // this never prints
}
i++;
}
});
Hi there are multiple ways to accomplish what you are trying.
However I think that there are some typos like the l % 2.
L does not increase and is the item length of your json thats why I changed it in my snippet.
Now to simplify the code above and get the output I guess you want:
const data1 = document.getElementById("data1");
const data2 = document.getElementById("data2");
const json = {
a: { picture: 'linkA', price_thingy: { suf: '€', price: 1.99 } },
b: { picture: 'linkB', price_thingy: { suf: '$', price: 1.99 } },
c: { picture: 'linkC', price_thingy: { suf: '£', price: 1.99 } },
d: { picture: 'linkD', price_thingy: { suf: '¥', price: 1.99 } },
}
const l = Object.keys(json).length;
let i = 0;
for (key in json) {
const value = json[key];
if (i % 2) {
// With this as syntax you don't have to use +
data1.innerHTML += `<img src="${value.picture}"/>`;
data1.innerHTML += value.price_thingy.price + value.price_thingy.suf;
} else {
data2.innerHTML += `<img src="${value.picture}"/>`;
data2.innerHTML += value.price_thingy.price + value.price_thingy.suf;
}
i += 1;
}
<div id='data1'></div>
<div id='data2'></div>

JQUERY + sign keep on adding on typing backspace key

Running below HTML and JS code to get value from JSON and render itself input field. Rendering and display works fine.
But when i try to edit the number, +90 98888222 (example) exists.. on typing backspace key, it repeatedly adding + sign. ex: +++++90 98888222. On each press of backspace, it adds the + sign.
This code in get function only causing the issue i think. Need to add + sign manually it front as JSON data response without + sign.
return CONTACT_MOBILE ? '+' + CONTACT_MOBILE.number : '';
Not sure how to block with 1 + when typing backspace.
Thanks
get: function() {
let CONTACT_MOBILE = _.find(this.updateProfile.contactList, (contact) => {
return contact.type == 'MOBILE';
});
return CONTACT_MOBILE ? '+' + CONTACT_MOBILE.number : '';
},
set: function(newValue) {
let CONTACT_MOBILE = _.find(this.updateProfile.contactList, (contact) => {
return contact.type == 'MOBILE';
});
if(CONTACT_MOBILE) {
CONTACT_MOBILE.number = '+' + newValue;
}
}
Use this :
set: function(newValue) {
let CONTACT_MOBILE = _.find(this.updateProfile.contactList, (contact) => {
return contact.type == 'MOBILE';
});
if(CONTACT_MOBILE) {
CONTACT_MOBILE.number = "";
if(!(newValue.charAt(0) === '+')){
CONTACT_MOBILE.number = '+';
}
CONTACT_MOBILE.number += newValue;
}
}

How can I delete Items from json string without using $.grep

I have a cart variable and I am storing the cart inside it like this.
[{"course_id":"24","doc_id":"211","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"217","doc_title":"PDF Notes","doc_price":"500"},{"course_id":"25","doc_id":"218","doc_title":"PDF Solved Past Papers","doc_price":"500"},{"course_id":"26","doc_id":"224","doc_title":"PDF Solved Past Papers","doc_price":"595"}]
I created a RemoveFromCart function. It works in simple JQUERY But it is not working in Framework 7 because of $.grep. Is there any other way I can do it without using $.grep?
This is my Function
function removeFromCart(course_id, doc_id) {
var x = confirm("Are you sure you want to remove this item from your cart?");
if (x) {
$$('#cart_body').html('');
existing_cart = localStorage.getItem("cart");
if (existing_cart == '') {
existing_cart = [];
} else {
existing_cart = JSON.parse(existing_cart);
}
existing_cart = $.grep(existing_cart, function (data, index) {
return data.doc_id != doc_id
});
ex_cart = JSON.stringify(existing_cart);
localStorage.setItem('cart', ex_cart);
existing_cart = localStorage.getItem("cart");
if (existing_cart == '') {
existing_cart = [];
} else {
existing_cart = JSON.parse(existing_cart);
}
if (existing_cart !== null && existing_cart.length > 0) {
var total = '';
$$('#cart_div').show();
existing_cart.forEach(function (arrayItem) {
var text = '';
text = '<li class="item-content"><div class="item-inner"><div class="item-title">' + arrayItem.doc_title + '</div><div class="item-after">' + arrayItem.course_id + '</div><div class="item-after">' + arrayItem.doc_price + '</div><div class="item-after"><i class="icon icon-cross" onclick="removeFromCart(' + arrayItem.course_id + ',' + arrayItem.doc_id + ')"></i></div></div></li>';
total = Number(total) + Number(arrayItem.doc_price);
$$('#cart_body').append(text);
});
text = '<tr><td></td><td class="text-center"><b>Total: </b></td><td class="text-center">' + total + '</td><td></td></tr>';
$$('#cart_body').append(text);
} else {
$$('#cart_div').hide();
text = '<p>Your cart is empty.</p>';
$$('#cart_body').append(text);
}
} else {
return false;
}
}
Instead of:
$.grep(existing_cart, function ...
You can use:
existing_cart.filter(function ...
var new_courses = existing_cart.map( v=> {
if(v.doc_id != doc_id)
return v
}).filter( v=> {return v})
// new_courses does not contain the course with doc_id
map loops through each member of an array. filter removes members not returned in map.

Loop through JSON & Compare time

What i'm trying to accomplish is to loop through this JSON, and compare the "start_time" and "end_time" to ensure the times don't overlap. I'm having trouble implementing this.
I found this: validate two times but none of it makes any sense nor is it using JSON but it's the closest i've found. Could I use jQuery to do this?
{
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
}
Expected output:
Audien & Slushii Conflict!
DJ Snake Does not Conflict with anyone!
Marshmello Does not Conflict with anyone!
*Notice Days 1 & 2
Here is a rather verbose prototype for your learning purposes. It uses moment.js and twix.js.
Demo: https://jsfiddle.net/JAAulde/5v7yksk3/4/
HTML for prototype code:
<ul id="output"></ul>
JS for prototye code
var data = {
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
},
tmp_day = '2000-01-01',
outer_key,
outer,
inner_key,
inner,
tmp_range,
checked = {},
conflict_found = {},
conflicts = [],
i;
for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key)) {
outer = data[outer_key];
tmp_range = moment(tmp_day + 'T' + outer.start_time).twix(tmp_day + 'T' + outer.end_time);
checked[outer_key] = true;
for (inner_key in data) {
if (Object.prototype.hasOwnProperty.call(data, inner_key) &&
outer_key !== inner_key &&
!checked[inner_key]
) {
inner = data[inner_key];
if (outer.day === inner.day &&
(
tmp_range.contains(tmp_day + 'T' + inner.start_time) ||
tmp_range.contains(tmp_day + 'T' + inner.end_time)
)
) {
conflict_found[outer_key] = true;
conflict_found[inner_key] = true;
conflicts.push([
outer_key,
inner_key
]);
}
}
}
}
}
// Output:
document.getElementById('output').innerHTML = '';
for (i = 0; i < conflicts.length; i++) {
document.getElementById('output').innerHTML += '<li><strong>' + data[conflicts[i][0]].artist + '</strong> conflicts with <strong>' + data[conflicts[i][1]].artist + '</strong></li>';
}
for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key) &&
!conflict_found[outer_key]
) {
document.getElementById('output').innerHTML += '<li><strong>' + data[outer_key].artist + '</strong> does not conflict with anyone</li>';
}
}
My solution:
var json = {
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1","start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"17:15",
"end_time":"15:15",
"stage":"horizon"
}
};
function timeToDate(timeStr) {
var whateverDate = '01/01/1980 ';
return Date.parse(whateverDate + timeStr);
}
for (item in json) {
var st = json[item].start_time;
var et = json[item].end_time;
var datesCorrect = (timeToDate(st) < timeToDate(et)) ? 'true' : 'false';
console.log(item + ' dates correct: ' + datesCorrect);
};
Demo: https://jsfiddle.net/dhf89twr/1/

Categories

Resources