Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141602 articles
Browse latest View live

Awaiting for a for loop to end to continue function in javascript

$
0
0

i have one question! I want the function getMealSummary() to return after the for loop has finished already finished (I didnt include the return key because the function is very big and i just had a doubt in this section).

How can I do it with async/await or promises?

Thanks

    export const getMealMicroSummaryHelper = async function getMealSummary(array, populatedFoods, customMeasurements, isRecipe,expertId){
  var [totalZinc, totalCalcium,totalAlphaCarotene,totalBetaCarotene,totalCholine,totalCopper,totalBetaCrypto,totalFluoride,totalVitaminB9,totalIron,
    totalLutein,totalLycopene,totalMagnesium,totalManganese,totalNiacin,totalVitaminB5,totalPhosphorus,totalPotassium,totalRetinol,totalRiboflavin,
    totalSelenium,totalSodium,totalTheobromine,totalVitaminA,totalVitaminB12,totalVitaminB6,totalVitaminC,totalVitaminD,totalVitaminD2,totalVitaminD3,
    totalVitaminE,totalThiamin] = [0, 0, 0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

  let recipesArray = []

  for(let i = 0; i < populatedFoods.length; i++){
       if(populatedFoods[i].foodType === 4){
            await apiCall("get",`/api/experts/${expertId}/recipes/${populatedFoods[i]._id}`)
          .then(recipe =>{
            recipesArray.push(recipe)
          })
          .catch((err)=>console.log(err))
        } 

Electron JS Input User Authentication

$
0
0

How do I make it so that the input user and input password is read and when the form is submitted, my desktop app transports me into a new html file? The basic user authentication stuff. I am quite stuck on this for days now

How to autosize a textarea using Prototype?

$
0
0

I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.

Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.

Here's a screenshot of it currently.

ISO Address

Any ideas?


@Chris

A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.

I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.

I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).

It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.

Though if someone comes up with another way to approach the problem I'm open to that too.


I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.

resizeIt = function() {
  var str = $('iso_address').value;
  var cols = $('iso_address').cols;
  var linecount = 0;

  $A(str.split("\n")).each(function(l) {
    linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
  })

  $('iso_address').rows = linecount;
};

How to convert JSON object to JavaScript array?

$
0
0

I need to convert JSON object string to a JavaScript array.

This my JSON object:

{"2013-01-21":1,"2013-01-22":7}

And I want to have:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');

data.addRows([
    ['2013-01-21', 1],
    ['2013-01-22', 7]
]);

How can I achieve this?

Band Display partially after animation

$
0
0

I have a container having a Band on top-left corner and I have added an animation to the container using animatelo library. Everything is working fine but after animation band get hidden partially. I don't know why?

The Container is overflow set to hidden.

BEFORE ANIMATION :

enter image description here

AFTER ANIMATION

enter image description here

DEMO

function animateDiv() {
  let container = document.querySelector(".container");
  window.animatelo.fadeInLeft(container, {
    duration: 400
  });
}
.container {
  width: 300px;
  overflow: hidden;
  margin: 15px 5px 5px 50px;
  padding: 15px;
  border: solid 1px;
}

.band {
  position: absolute;
  line-height: 1.5;
  margin: -26px 0 0;
  padding: 0 5px;
  font-weight: bold;
  background-color: white;
}
<script src="//cdn.rawgit.com/gibbok/animatelo/1.0.3/dist/animatelo.min.js"></script><div class="container"><div class="band" data-display="n">Band Title</div><div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin porttitor elit neque, in condimentum ante pulvinar et. Donec et erat nulla. </div></div><button type="button" onclick="animateDiv()">Animate</button>

GRAVITY FORMS: Unhide html-element on form submission (Wordpress)

$
0
0

I've tried to get this working for hours now, with many different methods and could not do it. Hopefully someone can help.

– I'm using Gravity Forms in Wordpress inside of an elearning lesson (which is part of a course) – As part of the elearning course there is a next-button (CSS class ".button-complete-lesson") which brings the user to the next lesson. – I don't want users to click this next-button without submitting the form first. – That's why this next-button is hidden via the main css of Worpress (display:none)

The goal: I need to show this button on form submission or after successful submission (doesn't matter). Meaning the Gravity Forms submit button should switch the css of the next-button from "display:none" to "display:block" without the need for a page reload.

I tried multiple approaches within my functions.php and none of them worked.

Colors in JavaScript console

$
0
0

Can Chrome's built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log's in green. Is that possible?

Move active element to favourite page in vue.js

$
0
0

I created a list with the best books. Every book have a 'like' icon. I would like to after click, this icon change colors, and this book now is available in "your favourite". But really I have no idea how show this book in "my favourite". Should I need some special 'id' or something to know whitch books is checked or not. Maybe somebody can promp me what is a logic of this features. I am using vue.js.


Why Chrome adds tbody tag to each table row? [duplicate]

$
0
0

I have two tables that fill up throw an event.

The stylesheet is made for that the even rows get painted white.

table {

border-collapse: collapse;
width: 100%;

}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}

But due Chrome adds tbody tag to each tr tag it's doesn't work.

The first table fill up throw back-end:

var prueba = {};
    prueba = nuevaCadena[nuevaCadena.length - 1].replace(/<br>/g, "").split(",");
    prueba.venta = prueba[0];
    prueba.fecha = prueba[1];
    prueba.heladeria = prueba[2];

    //prueba.base.split(",");

    //if (myElem === null) {
    var contenido = document.getElementById("contenido");
    var tr2 = document.createElement("TR");


    if (contenido.getElementsByTagName("TH").length === 0)
    {
        contenido.appendChild(tr2);
        tr2.innerHTML += "<th>Heladeria</th>";
        tr2.innerHTML += "<th>Fecha</th>";
        tr2.innerHTML += "<th>ID</th>";

    } else {
       var template = "<tr><td>{{heladeria}}</td><td>{{fecha}}</td><td>{{venta}}</td></tr>";

        document.querySelector('#contenido').innerHTML +=       Mustache.render(template, prueba);

   }

And the second works perfectly. It's fill up throw the select tag values.

var contenido = document.getElementById("contenido2");
var tr2 = document.createElement("TR");

var tr = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
contenido.appendChild(tr2);
tr2.innerHTML += "<th>Heladeria</th>";
tr2.innerHTML += "<th>Fecha</th>";
tr2.innerHTML += "<th>Sabor</th>";
tr2.innerHTML += "<th>Cantidad</th>";

}



contenido.appendChild(tr);

//var th = document.createElement("TD");
var option = ["heladerias", "sabores"];
var valor = document.getElementById("sabor_calorias");
var fecha = document.getElementById("fecha");


for (var i = 0; i <= 0; i++) {

var input = document.getElementById(option[i]).selectedIndex;
var input2 = document.getElementById(option[i]).options;

tr.innerHTML += "<td>" + input2[input].text + "</td>";
tr.innerHTML += "<td>" + fecha.value + "</td>";

for (var j = 1; j <= 1; j++) {

    input = document.getElementById(option[j]).selectedIndex;
    input2 = document.getElementById(option[j]).options;
    tr.innerHTML += "<td>" + input2[input].text + "</td>";
    tr.innerHTML += "<td>" + valor.value + "</td>";
    tr.innerHTML += "<input type='button' class='borrar' value='x'         onclick='deleted(this)'/>";

}


}

The results are this:

This question didn't work for me Why do browsers insert tbody element into table elements? i use Mustache.

Screenshot of Table

Screenshot of Chrome adding tbody

Firebase - set not working with new element

$
0
0

I'm trying to update my data in firebase using SET method but it's not working with no error.

Here's my flow:

  1. Push data to firebase
  2. Upload images
  3. Fetch the pushed data (step 1)
  4. Add the uploaded images (step 2) to the data
  5. Update the data (set)

I'm not sure if it will matter, but I'm using vuejs.

const post = {
title: payload.title,
description: payload.description
}


  let key
  let img = []

  firebase.database().ref('posts').push(post)
    .then((data) => {
      key = data.key
      return key
    })
    .then(key => {
      //im uploading images here

      //then I'm reaching to my post to add the uploaded images
  firebase.database().ref('posts/' + key).once('value')
        .then((data) => {
          const obj = data.val()
          const post_with_image = {
            title: obj.title,
            description: obj.description,
            images: imgs
          }

          console.log(post_with_image) //confirmed that "images" element is already added
          firebase.database().ref('posts').child(key).set(post_with_image) //but does not update with the images element
        })
    })

filter doesn't work in Vue.js. How can I fix it?

$
0
0

I'm trying to filter my array with data in Vue.js. I do it in computed property. This is the test array:

{
    "Animals": [
        {
            "date_time": "2011.08.31",
            "animal_list": [
                {
                    "animal_title": "Monkey"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        },
        {
            "date_time": "2012.08.31",
            "animal_list": [
                {
                    "animal_title": "Raccoon"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        }
    ]
}

And this is my filter function:

filteredData.filter(item =>
        item.animal_list.some(
          elem =>
            elem.animal_title
              .toLowerCase()
              .indexOf(this.animalTitle.toLowerCase()) != -1
        )
      );

It seems good, but doesn't work. When I enter "Raccoon" in the form, it must return only second object, but it returns all objects.

Why does it happen? What am I doing wrong?

UPD: filteredData is an Array. filteredData = animalData.Animals

Why use apply() or call() when you can pass the target object as a parameter?

$
0
0

I understand the use cases for using apply() and call(). You can essentially call a function from another object, and specify the this binding. This of course, only make sense if said function uses the this keyword.

What I don't understand, is, why would you create a function inside an object, and then decide that you want to reuse it somewhere else by changing this? To me it sounds like the function made sense in the first object, and rather than refactoring the function to live on its own, the programmer decided to just leave it there and call it with apply/call.

It would make more sense to me to take that function out of that object, and put it somewhere else where it's clearly visible that it can be used by different objects, by having it take that target object as an explicit parameter.

Am I missing something?

Using data from another class

$
0
0

I have a class in which I query to a DB some informations and I would to use these informations to display.

Class where I would to show data.

import React, { Component } from "react";
import FindUser from './FindUser';
let findUser = new FindUser();

class ShowProfile extends Component{
construct(props) {
super(props);
}
//...

render() {
    return (
      <View style={style.container}>
        <KeyboardAwareScrollView>
          <View style={style.page}>
            <Text style={visualProfilo.text}>Name:</Text>
            <Text style={visualProfilo.text1}>{this.state.FirstName}</Text>
            <Text style={visualProfilo.text}>Surname:</Text>
            <Text style={visualProfilo.text1}>{this.state.LastName}</Text>
//...
}

Class where I query the DB

class FindUser extends Component {
    constructor(props){
        super(props);
        this.state = {
        }
    }

    findUser(cf) {
        let params = {};
        params = {
          "Person.FiscalCode": cf
        };
        //... query to DB
          .then(response => {
            let utente = response.docs[0];
            console.log("name: ", user.Person.FirstName)

In this way I log the FirstName, than I would to use these informations to display as this.state.FirstName in ShowProfile. How can I do?

Checking if an HTML Element is in the Viewport

$
0
0

My Applescript that uses JavaScript inside it attempts to return true if an element is in the viewport.

So far, it's not working and returning “missing value” even though “var ele” is properly targetted and the browser is allowing JavaScript from Apple Events.

Any ideas on how to make it work?

tell application "Brave Browser" to tell active tab of front window
    execute JavaScript "

var ele = document.getElementsByClassName('tBJ dyH iFc SMy yTZ erh DrD IZT mWe')[0];

function isVisible (ele) {
  const { top, bottom } = ele.getBoundingClientRect();
  const vHeight = (window.innerHeight || document.documentElement.clientHeight);

  return (
    (top > 0 || bottom > 0) &&
    top < vHeight
  );
}
"

end tell

Handle long Web API TouchEvent in JavaScript while retaining default behavior in browser?

$
0
0

In addition to MouseEvents I'd like to use a "long"TouchEvent of a single finger/digit/input for my application (change mode, e.g. to start drawing or select elements to manipulate), while retaining all default actions like clicking/tapping, scrolling/swiping and hold-for-context-menu or hold-to-select.

In other words:

  1. a short touch (tap) should be analogous to a normal mouse click (usually emulated by browser)
  2. (short) touch and move (swipe) should cause normal scrolling
  3. a "longer" touch should be analogous to a mouse click-and-hold
  4. consequent move events should not cause scrolling but are handled by the application
  5. a long touch without move should cause normal secondary function (select, context-menu)
  6. pinch and other multi-touch gestures should use default handlers (for now)

There is no "hold-to-select" or similar event to my knowledge, so I am attempting to implement this myself.

Detecting a "long" touch before drag is quite simple (setTimeout(), e.g. How to detect a long touch pressure with javascript for android and iphone?), however, the initial touchstart already seems to trigger default event handlers, causing

  • no scrolling (intended)
    • Chrome on Windows
    • Chrome on Android
  • scrolling
    • Safari on iOS (iPhone)
    • Firefox on Windows and Android
  • secondary functions
    • select (not intended if move occurs)
    • Safari on iOS (iPhone)
    • context-menu (intended, when no move occurs)
    • Chrome on Windows: as intended (very long touch, no move)
    • Firefox on Windows: as intended (very long touch, no move)
    • Chrome on Android: none
    • Firefox on Android: none

on actual devices, despite preventDefault() and stopPropagation() calls from touchmove.

  • is there a "better" way already (an event I don't know about)?
  • is it possible to retroactively affect these envents/handlers (revert/undo events?)?
  • is there a way to determine the default actions (select, context menu) and the respective timeout (browser / OS implementation dependant)?

or

  • will I have to re-implement the very low-level handlers myself and then create and emit the necessary events (keeping different browser implementations in mind)?

Here's a preliminary (no touch on the device I'm writing this on, I'll update shortly to reproduce the behavior I'm seeing with my actual code) snippet for testing (feel free to improve/extend):

let t = document.getElementById("t");
t.innerHTML += navigator.userAgent + '<br/>'; 

// timer
var timerid;
var touchduration = 500;
var longtouch = false;
function lt(e){
  timerid = undefined;
  longtouch = true;
  e.preventDefault();
  e.stopPropagation();
  ls("LONG");
}
function ct(){if (timer)window.clearTimeout(timer);}

function ls(s){
  t.innerHTML += i + '' + s + '<br/>';  
  t.scrollTop = t.scrollHeight;
}

// log event
let i = 0;
let o = undefined;
function le(e){
  if (e.type!=o){
    ls( e.type + (longtouch?' LONG':'') );
    o = e.type;
    }
  i++;
};


//also: mousemove, mouseout, touchcancel
t.addEventListener("mousedown",  e=>{le(e);});
t.addEventListener("mouseup",    e=>{le(e);});
t.addEventListener("touchstart", e=>{le(e); 
  timer = window.setTimeout(lt, 500, e);
  });
t.addEventListener("touchend",   e=>{le(e);
  ct();
  longtouch = false;
  });
t.addEventListener("touchmove",  e=>{le(e);
  ct();
  if (longtouch) {
    e.preventDefault();
    e.stopPropagation();
    }
  });
<div id="t" style="height:10em; max-height:100%; overflow-y:scroll; border: 1px solid green;"/>

Javscript Math.Pow Multiplication [duplicate]

$
0
0

I want to multiply the result of Math.Pow by a double (2 decimals). Here is an example:

const number = 2.01*Math.pow(10,9);

Expected result: 2010000000

Actual Result: 2009999999.9999998

What causes this slight deviation? Is there a solution to this problem without rounding the incorrect number?

Firebase Storage put() method uploads an array of numbers instead of a string

$
0
0

I want to upload a string to a Firebase Storage file. I tried it with

let myString = '...';
storage.ref('path')
    .child('file.txt')
    .putString(myString, 'raw');

and with

let myString = '...';
storage.ref('path')
    .child('file.txt')
    .putString(btoa(myString), 'base64');

and with

let myString = '...';
let array = new TextEncoder("utf-8").encode(myString);
storage.ref('path')
    .child('file.txt')
    .put(myString);

but when I download the files via the Firebase Console, they are always encoded as a string representation of an char array. I.e. the text {"type":"a"} ends up as

123,34,116,121,112,101,34,58,34,97,34,124

which is the ASCII representation of

{"type":"a"}

This is the actual content of the file. Instead of characters, I get a comma-separated list of character codes.

Is that a bug, or am I doing something wrong?

WSO2 api gateway mediation sequence not threadsafe?

$
0
0

I'm facing an issue with a WSO2 custom out mediation sequence. The purpose of the sequence is to filter json response of an api depending of the caller application. I use the script mediator to load a js script and an include dynamic js script which has the name of the caller application.

The dynamic script is loaded with a property that is set with the expression $ctx:api.ut.application.name.

When the endpoint is called simultaneously by 2 distinct applications (let's call them app1 and app2), the included script can be the wrong one (app2 is calling and the property is set to app1).

Is the expression "$ctx:api.ut.application.name" thread safe ? Or the property "appli_rgpd" use a wrong scope ?

I run the version 2.6.0 of WSO2.

<sequence xmlns="http://ws.apache.org/ns/synapse"  name="filterRGPDPartnerSequence"><property name="JSONPayload" expression="json-eval($.)" /><property name="appli_rgpd"  expression="$ctx:api.ut.application.name"/><property name="keyDestination" expression="'repository/scripts/filterPartner'" scope="default" type="STRING"/><property name="dynamicKeyDestination" expression="fn:concat('repository/scripts/', get-property('appli_rgpd'))" scope="default" type="STRING"/><script language="js" key="{get-property('keyDestination')}" function="transform"><include key="{get-property('dynamicKeyDestination')}"/></script></sequence>

Validate work email address in JavaScript [closed]

$
0
0

What is a good regex to validate only work email addresses in a form using JavaScript? This function validate email addresses. I want to validate only work emails. How can I do that?

var email = document.getElementById('email');

function validateEmail() {
  var emailValue = document.getElementById('email').value;
  var pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
  if (emailValue.match(pattern)) {
    email.classList.remove("is-invalid");
  } else {
    email.classList.add("is-invalid");
  }
}

Check react input form for decimals and change value

$
0
0

In my current React application, I need an Input which validates and changes the outcome on the following rules:

Input: 10 -> Output: 1000
Input: 10.5 -> Output: 1050
Input: 10.55 -> Output: 1055

This is what I have so far:

<Form.Control
    as="input"
    type="number"
    min="0.00"
    step=".01"
    onChange={this.handleChange.bind(this)}
/>
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    if(event.target.value.includes('.')) {
        let values = event.target.value.split('.')
        if(values[1].length <= 1) {
            let decimal = values[1] = values[1] + '0';
            let output = values[0] + decimal;
        }
    }
    this.submitPayment(output) // error: output not defined
}

My problem is right now that my code only works if a decimal (point/comma) is entered.

Also I guess there is a much more "elegant" solution for this, which would be great to know!

Viewing all 141602 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>