Find an item and place it on my shopping cart - javascript

I'm learning both javascript and cypress, and I need your help, please... I want to find an item on a page, and add that item to the shoping cart.
I don't understand why I don't get any answer after .find. I don't get an error on cypress, but the item it's never added to the cart, and the cy.log dont display anyting.
/// <reference types="Cypress"/>
it ('ContarElementos', () => {
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares').should('have.length', 6)
})
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
cy.get ('#ProductosPopulares').eq(index).contains('ADD TO CART').click()
}
})
})
})
I know the place that has the item, so if I place it like this, it find appears on the cart, but I need it to work if I dont know the place on the list.
it ('Agregar elemento "top" al carrito de compra desde la pagina principal', function (){
cy.visit ('https://www.saucedemo.com/v1/inventory.html')
cy.get('.inventory_list >').as ('ProductosPopulares')
cy.get('#ProductosPopulares')
.find ('.inventory_item_name')
.each(($el,index,$list) => {
if($el.attr('.inventory_item_name') == 'Sauce Labs Onesie'){
cy.log ('Se encontró lo buscado')
}
})
cy.get ('#ProductosPopulares').eq(5).contains('ADD TO CART').click()
})

There is a mix-up between text and attribute, try swapping the .find() command and the .contains() command.
Something like this:
cy.contains('.inventory_list .inventory_item', 'Sauce Labs Onesie')
.find('button:contains("ADD TO CART")').click()

Related

How to save whether a user clicked a button or not, and if so run a function

I have two functions translate_fr and translate_en, onClick when you click FR or EN the paragraphs are swapped either to english or french by grabbing their id's with inner.html
These two functions run on every html page, but obviously when refreshed or changing pages the onclick function reverts back to normal. So for instance if the user presses the FR button I want all the translate_fr functions on the other pages to run once the page loads, swapping the english paragraphs to french.
I need a way to store the users button click with local storage, and then a conditional statement saying if the user pressed EN run function translate_en else if FR then run function translate_fr.
Is this possible? I am VERY new to JavaScript and unfamiliar with local storage. I have no way how to do this. Here is the website on its domain lionkuts.ca for any other reference. I put two paragraphs as an example, though as you can see in the image I did this for every paragraph in the website.
function translate_en(){
document.getElementById("intro").innerHTML = `Here at Lion Kuts we are a cat only establishment that offers a full range of services from complete grooming, bathing to boarding. You and your pet will be thrilled to know that only professional, natural and biodegradeable products are used, any sensitivities or allergies will not be a problem.`;
}
function translate_fr(){
document.getElementById("intro").innerHTML = `Chez Coupe Lion, nous ne sommes qu'un chat établissement offrant une gamme complète de services du toilettage complet, de la baignade à l'embarquement.Vous et votre animal sera ravi de savoir que seul un professionnel, des produits naturels et biodégradables sont utilisés, tout les sensibilités ou les allergies ne seront pas un problème.`;
}
<div class="wrapper3">
<button class="translate" id="click1" type="button"onclick="translate_en()">EN
</button>
<button class="translate" id="click2"
type="button" onclick="translate_fr()">FR
</button>
</div>
<p id="intro">
Here at Lion Kuts we are a cat only
establishment that offers a full range of services
from complete grooming, bathing to boarding. You and
your pet will be thrilled to know that only professional,
natural and biodegradeable products are used, any
sensitivities or allergies will not be a problem.
</p>
You can use Window.localStorage to save the current language, and then use Window.onload to check the language.
Window.localStorage
Window.onload
function translate_en(){
Window.localStorage.setItem("language", "EN");
//translate the web page
} //translate_fr is same, but with french
Window.onload = (e) => {
let language = Window.localStorage.getItem("language");
if(language === "EN"){
translate_en();
} else if(language === "FR"){
translate_fr();
} else {
translate_en();//Default (if null)
}
}

How to add translatable string in function parameter?

I have a javascript function in a wordpress script, I need it to be compatible with WPML chain translation
ubp_show_error("<p>Inutile de l'ajouter plusieurs fois</p>");
How can I make this chain to be something like this :
ubp_show_error(_e('<p>Inutile de l'ajouter plusieurs fois</p>','mytheme'));
I've tryed :
$error = _('<p>Inutile de l'ajouter plusieurs fois</p>','mytheme');
ubp_show_error($error);
but in javascript, this doesn't work
You need to localize your script.
PHP
function custom_load_scripts() {
wp_enqueue_script('your-script', '/your-script.js');
wp_localize_script('your-script', 'your_js_obj_name', array(
'error' => __("<p>Inutile de l'ajouter plusieurs fois</p>",'mytheme')
)
);
}
add_action('wp_enqueue_scripts', 'custom_load_scripts');
Now you have access to that data in your javascript file like:
JS
your_js_obj_name.error // --> '<p>Inutile de l'ajouter plusieurs fois</p>'

How to manipulate a JSONArray in JQuery

i have a php function which returns me this code in JSON
{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9atrice"},"2":{"title":"Visite chez Jean-Louis"},"3":{"title":"Anita \u00e0 la matenit\u00e9"},"4":{"title":"Visite chez Jean-Louis 2"},"5":{"title":"H\u00e9l\u00e9na pr\u00e9sent\u00e9e \u00e0 la famille"},"6":{"title":"Chez des proches"},"7":{"title":"Soir\u00e9e souvenir avec un proche - Photos, histoires"},"8":{"title":"Douceline tenant un b\u00e9b\u00e9"},"9":{"title":"Visite chez Jean-Louis 3"},"10":{"title":"Bapt\u00eame de Alexandra - Dans l\u2019\u00e9glise"}}
and i want to manipulated in JQuery I’ve did this but it doesn’t work
$.each(json, function(item, value) {
console.log(value);
$.each(value, function() {
console.log(this.title);
});
});
any ideas thanks a lot
The first traversal using each provides you the object containing the value of title field.
So , Simply fetch the value using :
$.each(json, function(item, value) {
alert(value.title);
});
And here is the demo jsfiddle

Why do these 2 alerts show different values?

I restart from begining.
My intranet webpage works like this:
1) User load the page, I load my motor database with $.Post in an array named motorsFull.
// load from my motor database
$.post("ajax.php?action=chargementBases",
function(data) {
motorsFull = data[0];
},"json");
// array built in ajax.php
$query = mysql_query("SELECT * FROM details_moteurs ORDER BY m_update_id DESC");
$i=0;
while ($infosMoteurs = mysql_fetch_assoc($query)) {
$arrayMoteur[$i] = $infosMoteurs;
$i++;
}
2) when user type in a research field I filter my array motorsFull and copy from it the lines matching the keywords with a function.
3) Every line of my motor database is an update, so you can have 3..10..25 entry for one motor id. This allow me to save all the change done by all users.
4) When a search is done, after filtering my motorsFull array I return the 10 first lines under motorsToDisplay array to my display update function.
5) To get the last value displayed on the user screen, for the 10 first motors returned I look for updates in my motorsFull array and update each cell of motorsToDisplay depending on some parameters with the following code. (All the code is not there only the update of the data for each different motor found).
for (var k=0; k < motorsFull.length;k++ )
{
//si on est sur le même moteur et que le n° d'update est différent
if(motorsToDisplay[i]['m_id'] == motorsFull[k]['m_id'] && motorsToDisplay[i]['m_update_id'] != motorsFull[k]['m_update_id']){
//historique k plus ancien que i
if(motorsFull[k]['m_last_update'] > motorsToDisplay[i]['m_last_update']){
// pour chaque case de la ligne en cours
for (var positionDansLigne in motorsToDisplay[i]){
//si la case récente est vide
if(motorsFull[i][positionDansLigne] == '')
{
// si la case ancienne n'est pas vide
if(motorsFull[k][positionDansLigne] == ''){
if(positionDansLigne != 'm_update_id' && positionDansLigne != 'm_user_done_update'&& positionDansLigne != 'm_update_type'&& positionDansLigne != 'm_update_comment'&& positionDansLigne != 'm_id'&& positionDansLigne != 'm_last_update'){
//on ecrase la valeur vide par l'ancien historique
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
}
}
}
}
}
else{
//historique k plus récent que i
// pour chaque case de la ligne en cours
for (var positionDansLigne in motorsToDisplay[i]){
// si la case du tableau plus récent n'est pas vide
if(motorsToDisplay[k][positionDansLigne] != ''){
if(positionDansLigne != 'm_update_id' && positionDansLigne != 'm_user_done_update'&& positionDansLigne != 'm_update_type'&& positionDansLigne != 'm_update_comment'&& positionDansLigne != 'm_id'&& positionDansLigne != 'm_last_update'){
//on ecrase la valeur par le nouvel historique
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
}
}
}
}
}
}
6) My problem start here. I dont know why but the first time I read my motorsFull everthing is okay, but after I readed it the data are updated like I done in my array motorsToDisplay with the function above. Nowhere in my code I update any value from motorsFull.
6b) I wrote following code to display you the content of my array motorsFull for a specific motor after and before it was read.
var textDebug ='';
for (var k=0; k < motorsFull.length;k++ )
{
if(motorsFull[k]['m_id']=='507'){
textDebug+='\r\r Line '+k+': ';
for (var y in motorsFull[k]){
textDebug+='['+ motorsFull[k][y]+'] ';
}
}
}
alert(textDebug);
7) If anyone could explain me why I dont read the same data twice from motorsFull, or why this array is updated it could help me. I can also provide the complete code but it is over 1000 lines :-)
Before
===================================================
After
Hint: If this line is commented my motorsFull dosen't change.
motorsToDisplay[i][positionDansLigne] = motorsFull[k][positionDansLigne];
EDIT: Here is my complete code (without ajax.php)
http://www.mediafire.com/view/dc48wv0voiqnuuw/fonctionsMoteurs.js
http://www.mediafire.com/view/j4uj4daztfyzai5/moteurs.php
I can't read the mediafire code (says "loading" indefinitely, and I've no idea whether I need an account or what else), but --
You have a non-trivial data structure (arrays of dictionaries), for which I did not see the initialization: I suspect that when populating motorsToDisplay and motorsToDisplay you at some time put the same dictionary into both.
Changing a dictionary by saying dict['key'] = value will change the dictionary, i.e., the change will of course change the dictionary, which when used two times, shows the change in two places.
Please check whether you can find a
motorsToDisplay[i] = motorsFull[k];
or a
dict = { ... };
motorsToDisplay[i] = dict;
motorsFull[k] = dict;
somewhere...

Send extra params to a view on backbone.js

I was trying the solutions that suggest in this questions but it don't work
How to pass parameters to a view
How can I pass a parameter into a Backbone.js view?
Backbone.js - passing arguments through constructors
I am trying to pass extra parameter to use in my template, I read that all extra params that I pass I can have access to them in this.options.varName but it dont work for me.
heres the controller code:
servicios : function(){
//Crea la colecion de tipos de servicios municipales
//Crea el modelo para dar de alta un nuevo reporte de servicio municipal
var reporteServicioSingle = new ReporteServicioSingle();
//Crea la vista para la pantalla de servicios municipales
var servicios_view = new Servicios({
model : reporteServicioSingle,
collection : this.reportes,
tipos : this.tipos
});
// Carga la vista renderisada y inicializa foundation
$("#app-content").html(servicios_view.render().el);
$(document).foundation();
},
And this is my view code:
render: function(){
console.log(this.options.tipos);
this.$el.html(Handlebars.templates.servicios(this.collection));
$(document).foundation();
return this;
},
but the chrome developers console, send me an error that options is not definided.
Uncaught TypeError: Cannot read property 'tipos' of undefined
Thank you and sorry for my bad english.
Assuming you're using Backbone 1.1, it no longer attaches the options argument to this.options automatically anymore, a shitty change (imho).
You'll need to extend the options parameter yourself in your initialization method:
initialize: function(options) {
this.options = _.omit(options, ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']);
}

Categories