HTML tooltip using only div/span/etc. attributes (onmouse…/style/etc.)

I work with a website that has a rich text box which gives direct access to the underlying HTML code. I can edit the HTML code, but when I save it, the website intervenes. <style> elements disappear, but <div> and <span> elements remain and seem to keep all their attributes.

I would like a certain <span> element to show a tooltip when hovered over. I’ve considered using the title attribute (it works), but it’s not flexible enough for my need.

Is it possible (and how) to implement a tooltip like shown here without a <style> element, using only attributes of <div> and <span> elements? I was thinking of attributes such as style, onmouseover, and onmouseout, but feel free to suggest other ones as you see fit.

Unable to get a selected image src to get copied to a file input refs

I have been on this for a full day and I just cannot find an answer to it.

Imagine a form with an upload file input field. Next to it there is also a button called “select template”. The user can either upload his own image or select an image from a given template.

Here is the problem, I am unable to send the selected image to the input field(so I can process it in my axios post later on).

This is the table where all the template files are showing up:

<table class="table table-borderless table-hover">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="item in image_gallery">
<td class="align-middle">{{ item.id }}</td>
<td class="align-middle">{{ item.title }}</td>
<td><img :src="'/storage/images/' + item_image" class="img-thumbnail" alt="" style="width: 75px;" @click="selectImage(item.id, $event)">
</td>
</tr>
</tbody>
</table>

When the user clicks on the above image, I would like the file to be set to this input field(which is the same input where the user can upload his own file).

<label class="btn btn-info btn-block btn-sm">
<i class="fas fa-upload text-white"></i>
<input
type="file"
id="file"
@change="onFileAttached(1)"
ref="file"
accept="image/png, image/jpeg"
hidden/>
</label>

I tried this:

selectImage(id, event){

this.$refs.files[0].src = event.files[0].src;
//or
this.$refs.files[0].src = event.target.src;
}

But no luck…..I am not understanding what I am missing 🙁

Is there a way to manually take a URL from a given image to set this image to an input field?

Thanks in advance for guiding me a bit.

How to set function to button to uncheck radios inside a loop

I created table with a double loop.
For every cell i put 3 radios and a button that should uncheck the radios.
I can’t do that because the functions inside the loop can’t identify the correct radio (that has id based on 2 vars: ‘NP’+medici[cas]+colonne[col]).
If I put the function outside the loop:

  • if I put the function after the loop I get “function not declared” error
  • if I put the function before the loop I get “Cannot set properties of null (setting ‘checked’)”

This is the function

for(let cas=0; cas<6; cas++){
        
[...]
    for  (var col=1; col<6; col++){
[...]
var radioboxNM = document.createElement('input');
  radioboxNM.type = 'radio';
  radioboxNM.id = 'NM'+medici[cas]+colonne[col];
  radioboxNM.value = 'NM'+medici[cas]+colonne[col];
  radioboxNM.name = 'radio'+medici[cas]+colonne[col];
  var label = document.createElement('label')
  label.htmlFor = 'NM';
  var description = document.createTextNode('NM');
  label.appendChild(description);
    const newline = document.createElement('br');
 tbodyTdAss.appendChild(radioboxNM);
 tbodyTdAss.appendChild(label);
 
  //crea radio NP
          var radioboxNP = document.createElement('input');
                radioboxNP.type = 'radio';
                radioboxNP.id = 'NP'+medici[cas]+colonne[col];
                radioboxNP.value = 'NP'+medici[cas]+colonne[col];
          radioboxNP.name = 'radio'+medici[cas]+colonne[col];
                var label = document.createElement('label');
                label.htmlFor = 'NP';
                    var description = document.createTextNode('NP');
      label.appendChild(description);  
        tbodyTdAss.appendChild(radioboxNP);
      tbodyTdAss.appendChild(label);
            tbodyTdAss.appendChild(newline);
//Crea radio assente
          var radioboxAss = document.createElement('input');
                radioboxAss.type = 'radio';
                radioboxAss.id = 'Ass'+medici[cas]+colonne[col];
                radioboxAss.value = 'Ass'+medici[cas]+colonne[col];
          radioboxAss.name = 'radio'+medici[cas]+colonne[col];
                var label = document.createElement('label');
                label.htmlFor = 'Ass';
                    var description = document.createTextNode('Ass');
      label.appendChild(description);  
        tbodyTdAss.appendChild(radioboxAss);
      tbodyTdAss.appendChild(label);
// crea bottone reset
buttonX[cas][col] = document.createElement('button');
buttonX[cas][col].innerText = 'Canc';
buttonX[cas][col].id = 'buttonX'+medici[cas]+colonne[col];
buttonX[cas][col].setAttribute("onClick", cancellaRadio(cas,col));
[...]

This is the function:

cancellaRadio = function (cas,col) {
    document.getElementById('NM'+medici[cas]+colonne[col]).checked = false;
  document.getElementById('NP'+medici[cas]+colonne[col]).checked = false;
  document.getElementById('Ass'+medici[cas]+colonne[col]).checked = false;
         }; 

Any ideas?

Accessing children of children in ThreeJS

I’ve been learning ThreeJs and boy did I get stuck trying to call my files.

Let me start by explaining what I wanted to do!
i have 3 models to display on a page, as people scroll a different emoji should be displayed, like small sections, classic webapge way.

I imported these models from blender in one gltb file to improve performance, and theorically, save time, two of the objects are groups and the other is a mesh. There’s nothing else in the import.

However after using gltf loader to load my models I can’t find a way to access them to accomodate them in the positions and rotations I want them to be at. Please help.

I loaded my scene:

gltfLoader.load(
'EMOJIS.gltf',
(gltf) =>
{
    gltf.scene.scale.set(0.25, 0.25, 0.25)
    gltf.scene.position.set(0, 0, 0)

    mixer = new THREE.AnimationMixer(gltf.scene)
    scene.add(gltf.scene)
}

After that I checked my log to reach for the objects

console.log(scene)
console.log(scene.children)
console.log(scene.children[3])

The first and second log show as follows:

enter image description here

I realized that I should reach the children of the scene’s children to get my 3 emojis: heart, peach, heartEyes.
I thought I could just call scene.children[3].children[0] for example. and call the heart object emoji
But I cant call them? I have tried many ways but it always shows as undefined.

console.log(scene.children) shows an array from 0 to 3, in the [3] slot I can see the emoji elements I want, but calling console.log(scene.children[3]) shows undefined, how can I access the group I want?

Calling

var heart = scene.getObjectByName( "heart", true );

or calling by their ID (which are 16, 15 and 23) shows undefined as well.

All help is very much appreciated.

Why socket.io keeps the variable from the last request?

I’m trying to make a simple web socket for my application, but I have problems with the find method.

const io = require('socket.io')(3002, { cors: { origin: 'http://localhost:3000' } })
const api = require('axios').create({ baseURL: 'http://localhost:3001/api', timeout: '5000' })

let users = []

async function verify(user, usePassword){
    let verified

    await api.get(`/users/get?username=${user.username}`)
    .then(() => verified = true)
    .catch(() => verified = false)

    if(usePassword){
        await api.post('/users/login', { data: { username: user.username, password: user.password } })
        .then(() => verified = true)
        .catch(() => verified = false)
    }
}

io.on('connection', (socket) => {
    socket.on('statusOnline', async (user) => {
        if(!user || !user.username || !user.password) return io.to(socket.id).emit('error', 'Invalid user object')
        const isVerified = verify(user, true)
        if(!isVerified) return io.to(socket.id).emit('error', 'Problem with verifying you')

        users.push({ username: user.username, password: user.password, socketId: socket.id })
        console.log(users)
    })

    socket.on('messageSend', async (user, conversationId) => {
        if(!user || !user.username || !user.password) return io.to(socket.id).emit('error', 'Invalid user object')
        if(!conversationId) return io.to(socket.id).emit('error', 'No conversation id provided')
        if(conversationId.length < 12) return io.to(socket.id).emit('error', 'ConversationId must be longer then 12 characters.')
    
        const isVerified = verify(user, true)
        if(!isVerified) return io.to(socket.id).emit('error', 'Problem with verifying you')
    
        const conversation = await api.get(`/conversations/get?conversationId=${conversationId}`)
        if(!conversation?.data?.members?.find((m) => m == user.username)) return socket.to(socket.id).emit('error', 'You are not in that conversation.')
    
        const recieverUsername = conversation.data.members.find((m) => m.username != user.username)
        const reciever = users.find((u) => u.username == recieverUsername)
        if(!reciever) return
    
        io.to(reciever.socketId).emit('messageRecieve', conversation.data._id)
    })

    socket.on('disconnect', () => {
        const user = users.find((u) => u.socketId == socket.id)
        console.log('Someone disconnected')
        users = users.filter((u) => u.socketId != socket.id)
    })
})

As you can see I have a messageSend event. The purpose of that event is to notify the reciever that he got new message.

The problem is:

Lets say that the User1 wanna send message to the User2. The User1 opens the app and sends the message. It works fine.
When the User2 wanna reply, it doesen’t.

I tryed logging the users, recieverUsername and reciever variables and discovered that the reciever is always the User1. When User2 sends the first message, reciever is always User2.

If someone know what is going on here, please help me.

JavaScript Snake Game Reset Button

I am making a javascript snake game for my computer science class. It is due on Friday and I need help. I need to create a reset button but I’m not sure how to. Can someone help? Code is posted below.

*This is the index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            margin: 0px;
            padding: 0px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        canvas{
            box-shadow: black 20px 10px 50px;
        }
    </style>    
</head>

<body>
    <h1>Snake</h1>
    
    <canvas id="game" width="400" height="400"/>
    <script src="index.js"></script>
    
</body>
</html>


This is the index.js
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

class SnakePart {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}


let speed = 7;

let tileCount = 20;
let tileSize = canvas.width / tileCount - 2;

let headX = 10;
let headY = 10;
const snakeParts = [];
let tailLength = 2;

let appleX = 5;
let appleY = 5;

let inputsXVelocity = 0;
let inputsYVelocity = 0;

let xVelocity = 0;
let yVelocity = 0;

let score = 0;

const gulpSound = new Audio("gulp.mp3");

function drawGame() {
  xVelocity = inputsXVelocity;
  yVelocity = inputsYVelocity;

  changeSnakePosition();
  let result = isGameOver();
  if (result) {
    return;
  }

  clearScreen();

  checkAppleCollision();
  drawApple();
  drawSnake();

  drawScore();

  if (score > 5) {
    speed = 9;
  }
  if (score > 10) {
    speed = 11;
  }

  setTimeout(drawGame, 1000 / speed);
}

function isGameOver() {
  let gameOver = false;

  if (yVelocity === 0 && xVelocity === 0) {
    return false;
  }

  if (headX < 0) {
    gameOver = true;
  } else if (headX === tileCount) {
    gameOver = true;
  } else if (headY < 0) {
    gameOver = true;
  } else if (headY === tileCount) {
    gameOver = true;
  }

  for (let i = 0; i < snakeParts.length; i++) {
    let part = snakeParts[i];
    if (part.x === headX && part.y === headY) {
      gameOver = true;
      break;
    }
  }

  if (gameOver) {
    ctx.fillStyle = "white";
    ctx.font = "50px Verdana";

    if (gameOver) {
      ctx.fillStyle = "white";
      ctx.font = "50px Verdana";

      var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
      gradient.addColorStop("0", " magenta");
      gradient.addColorStop("0.5", "blue");
      gradient.addColorStop("1.0", "red");
      ctx.fillStyle = gradient;

      ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
    }

    ctx.fillText("Game Over!", canvas.width / 6.5, canvas.height / 2);
  }

  return gameOver;
}

function drawScore() {
  ctx.fillStyle = "white";
  ctx.font = "10px Verdana";
  ctx.fillText("Score " + score, canvas.width - 50, 10);
}

function clearScreen() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function drawSnake() {
  ctx.fillStyle = "green";
  for (let i = 0; i < snakeParts.length; i++) {
    let part = snakeParts[i];
    ctx.fillRect(part.x * tileCount, part.y * tileCount, tileSize, tileSize);
  }

  snakeParts.push(new SnakePart(headX, headY)); 
  while (snakeParts.length > tailLength) {
    snakeParts.shift(); 
  }

  ctx.fillStyle = "orange";
  ctx.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize);
}

function changeSnakePosition() {
  headX = headX + xVelocity;
  headY = headY + yVelocity;
}

function drawApple() {
  ctx.fillStyle = "red";
  ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}

function checkAppleCollision() {
  if (appleX === headX && appleY == headY) {
    appleX = Math.floor(Math.random() * tileCount);
    appleY = Math.floor(Math.random() * tileCount);
    tailLength++;
    score++;
    gulpSound.play();
  }
}



document.body.addEventListener("keydown", keyDown);

function keyDown(event) {

  if (event.keyCode == 38 || event.keyCode == 87) {
 
    if (inputsYVelocity == 1) return;
    inputsYVelocity = -1;
    inputsXVelocity = 0;
  }


  if (event.keyCode == 40 || event.keyCode == 83) {

    if (inputsYVelocity == -1) return;
    inputsYVelocity = 1;
    inputsXVelocity = 0;
  }


  if (event.keyCode == 37 || event.keyCode == 65) {

    if (inputsXVelocity == 1) return;
    inputsYVelocity = 0;
    inputsXVelocity = -1;
  }


  if (event.keyCode == 39 || event.keyCode == 68) {

    if (inputsXVelocity == -1) return;
    inputsYVelocity = 0;
    inputsXVelocity = 1;
  }
}

drawGame();

The game works otherwise, I just need a reset button! Can someone please reply with the right code and where to put it! Thanks so much.

Is there an issue with scope in this es6 function preventing these variables from being equivalent?

I’m new to es6, using const and the overall implications that has on the scope of a function. Whenever this function is output, it always says it failed to add all items. Is there something glaringly obvious preventing the loaded const from equaling the total const?

const addContent = function() {
  const getTotal = function() {
    const total = Number("`3");
    return total;
  };
  let content = "<div><span>";
  const loaded = 3;
  const total = getTotal();
  for (let i = 0; i < loaded; i++) {
    content += "<h2>Test " + i + "</h2>";
  }
  const results = loaded == total ? "<h3>Added all of the items.</h3>" : "<h3>Failed to add all of the items.</h3>";
  content += results + "</span></div>";
  return content;
};

how to popup form with django formset

i’ve have application in the home page there shows some posts with a contact form, i want to create a modal formset in another view! is it possible please ?

@login_required
def addPopupVistor(request):
    formset = VistorFormSet(queryset=Vistor.objects.none(),prefix='formsetvisitor')
    if request.is_ajax() and request.method == 'POST':
        formset = VistorFormSet(request.POST,prefix='formsetvisitor')
        if formset.is_valid():
        for form in formset:
            obj = form.save(commit=False)
            if form.cleaned_data !={}:                    
                obj.admin = request.user
                obj.save()
                return JsonResponse({'success':True})
    else:
        return JsonResponse({'success':False,'error_msg':formset.errors})

return render(request,'main/home.html',{'formsetvisitor':formset})

    const addNewFormRow = document.getElementById('addPopUpButton')
    const totalNewPopUpForms = document.getElementById('id_formsetvisitor-TOTAL_FORMS')
    addNewFormRow.addEventListener('click',add_new_popuprow);

    function add_new_popuprow(e){            
    if(e){
        
        e.preventDefault();
    }  
    const currentFormPopUpClass = document.getElementsByClassName('popup_modal_formset')

    const countpopupForms = currentFormPopUpClass.length        

    const formCopyPopupTarget = document.getElementById('visitorform')

    const empty_form = document.getElementById('empty_popup_formset').cloneNode(true);        
    empty_form.setAttribute('class','relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset')
    empty_form.setAttribute('id',`form-${countpopupForms}`)
    const rgx = new RegExp('__prefix__','g')
    empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countpopupForms)

    totalNewPopUpForms.setAttribute('value',countpopupForms + 1)
    formCopyPopupTarget.append(empty_form)

    }
<button onclick="modal()" class="some css class">add new guest</button>

<div id="modal" class="w-full fixed top-0 md:overflow-y-scroll hidden flex flex-wrap p-1 h-screen justify-center items-center bg-black opacity-90" style="z-index: 99999;">
    <div class="w-full md:w-10/12 p-2 bg-white rounded-xl">
        <button id="addPopUpButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl">
            {% trans "add new form" %}
            <i class="fas fa-plus"></i>
        </button>
        <form method="POST" class="mt-2" id="addnewguests">{% csrf_token %}

            {{formsetvisitor.management_form}}
            
            <div id="visitorform" class="grid md:grid-cols-3 gap-16 md:gap-x-3 md:gap-y-8">
                {% for form in formsetvisitor.forms %}
                {{ form.pk }}    
                {{form}}
                <!-- first form -->
                <div class="relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 popup_modal_formset">
                
    
                    <div class="relative groupinput bglightpurple rounded-xl">
                        <label class="absolute mt-1 mr-2 text-xs text-white top-1">full name</label>
                        {{form.full_name | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}

                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                            <label class="absolute mt-1 mr-2 text-xs text-white top-1">dob</label>
        
                            {{form.dob | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                            {% if form.dob.errors %}
                            <p class="w-full pb-2 pr-2 text-white rounded-xl" id="dob_error">{{form.dob.errors}}</p>
                            {% endif %}
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">city </label>
                                {{form.city | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none city'}}
                                {% if form.city.errors %}
                                <p class="pb-2 pr-2 text-white rounded-xl" id="city_error">{{form.city.errors}}</p>
                                {% endif %}
                        </div>
                    </div>
        
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">nation</label>
                                {{form.nation | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                {% if form.nation.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="nation_error">{{form.nation.errors}}</p>
                                {% endif %}
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">gender </label>
                                {{form.gender | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent'}}
                                {% if form.gender.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="gender_error">{{form.gender.errors}}</p>
                                {% endif %}
                        </div>
                    </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">job </label>
                                {{form.job | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                {% if form.job.errors %}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="job_error">{{form.job.errors}}</p>
                                {% endif %}
        
                        </div>
                </div>                    
                {% endfor %}
            </div>
            
                <div class="relative p-2 bg-gray-900 bg-opacity-25 border border-gray-900 rounded-xl pb-14 hidden" id="empty_popup_formset">                   
                    <div class="relative groupinput bglightpurple rounded-xl">
                        <label class="absolute mt-1 mr-2 text-xs text-white top-1">full name</label>
                        {{formsetvisitor.empty_form.full_name | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                        {% if formsetvisitor.empty_form.full_name.errors %}
                        <p class="w-full pb-2 pr-2 text-white rounded-xl" id="full_name_set_error" >{{formsetvisitor.empty_form.full_name.errors}}</p>
                        {% endif %}
                    
        
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">dob</label>
                                {{formsetvisitor.empty_form.dob | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="dob_set_error">{{formsetvisitor.empty_form.dob.errors}}</p>
        
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">city</label>
                                {{formsetvisitor.empty_form.city | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="city_set_error" >{{formsetvisitor.empty_form.city.errors}}</p>
        
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 md:gap-1">
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">nation</label>
                                {{formsetvisitor.empty_form.nation | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="nation_set_error" >{{formsetvisitor.empty_form.nation.errors}}</p>
        
                        </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">gender </label>
                                {{formsetvisitor.empty_form.gender | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="gender_set_error" >{{formsetvisitor.empty_form.gender.errors}}</p>
        
                        </div>
                    </div>
                        <div class="relative mt-2 groupinput bglightpurple rounded-xl">
                                <label class="absolute mt-1 mr-2 text-xs text-white top-1">job </label>
                                {{formsetvisitor.empty_form.job | add_class:'w-full pt-6 pb-1 pr-2 text-white bg-transparent focus:outline-none'}}
                                <p class="w-full pb-2 pr-2 text-white rounded-xl" id="job_set_error" >{{formsetvisitor.empty_form.job.errors}}</p>
        
                        </div>
        
                    </div>    
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse rtl">
                <input name="visitorformbtn" type="submit" class="some css class" value="{% trans "save" %}">
                    
                <button id="cancel" class="some css class">
                    {% trans "cancel" %}
                </button>
              </div>
    
        </form>
    
    </div>
</div>

but i dont have any idea how to call back it in the home page without make it in the home view ? and the form will go through ajax request to save the forms, but i dont know how to call the form inputs into the home template .
i appreciate any idea

How to duplicate every index of an array with Javascript?

I’m struggling with this because all search engine results are about find duplicates in array. And I want exactly the opposite.

I have an array of colors:

const colors = ["#fff", "#666", "#000"];

How do I simply duplicate or triplicate every one of its indexes?

x2: ["#fff", "#fff", "#666", "#666", "#000", "#000"];

x3: ["#fff", "#fff", "#fff", "#666", "#666", "#666", "#000", "#000", "#000"];

x…

How to change product version with Electron Builder (Windows)?

I am using Electron Builder to build an Electron app. I would like the executable to have a product version that is different from the package.json version.

This is what the build instruction in package.json looks like:

"build": {
    "appId": "myAppId",
    "productName": "My App",
    "copyright": "Copyright (C) 2022 My Company",
    "artifactName": "My App.exe",
    "directories": {
        "output": "dist/My App"
    },
    "buildVersion": "1.0.0.1"
},

I thought that buildVersion would update the product version, but when I look at the details of the .exe file, the product version has remained the same as the version number in package.json (1.0.0):

App details

How can I solve this?

VueJS : How can I pre-populate my input with data from API?

I have an edit form, and I’m trying to populate my input base on the response from API. My campaign data look like this.

{
    "id": 219,
    "name": "finishedddd-1642606412049"
}

enter image description here

Testing

You see that I can access campaign.name like this

<p>Campaign Name : {{ campaign.name }}</p>

Trying

I want to pre-populated my name input, so I did this

data() {
    return {
        campaign: {},
        form: {
            errors: {},
            values: {
                name: this.campaign.name,
                ...

Result

Somehow that kept getting me :

“TypeError: Cannot read properties of undefined (reading ‘name’)”

enter image description here

Code

<template>
    <v-container fluid class="my-1">
        <Navbar />
        <Breadcrumbs />
        <v-row>
            <v-col cols="12">
                <v-card elevation="2">
                    <PanelHeader type="create" icon="campaign" title="Campaigns" />

                    <v-stepper v-model="e1" justify="center" elevation="0">
                        <v-stepper-header>
                            <v-stepper-step :complete="e1 > 1" step="1"> Campaign </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step :complete="e1 > 2" step="2"> Setup </v-stepper-step>
                            <v-divider></v-divider>
                            <v-stepper-step step="3"> Finish </v-stepper-step>
                        </v-stepper-header>

                        <v-stepper-items>
                            <v-stepper-content step="1">
                                <v-card class="mb-12" elevation="0">
                                    <v-form ref="form" lazy-validation v-model="valid" id="form">
                                        <v-row>
                                            <v-card-text class="font-weight-bold">
                                                Campaigns

                                                <p>Campaign Name : {{ campaign.name }}</p>

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Select marketing campaign type for Print Materials or Product Tags. Provide a name to identify the marketing campaign.</span>
                                                </v-tooltip>
                                            </v-card-text>
                                        </v-row>

                                        <v-row>
                                            <v-col class="col-sm-2 col-lg-2 col-12">
                                                <v-select disabled dense outlined :items="types" label="Type" v-model="form.values.type" :rules="form.rules.type"></v-select>
                                            </v-col>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-text-field dense outlined v-model="form.values.name" :rules="form.rules.name" label="Name" required></v-text-field>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="6" md="4">
                                                <v-textarea dense rows="1" outlined v-model="form.values.description" label="Description" required></v-textarea>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-card-text class="font-weight-bold"
                                                >Schedule :

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Set the time zone, start and end date for this campaign to be active.</span>
                                                </v-tooltip>
                                            </v-card-text>

                                            <v-col cols="12" sm="6" md="4">
                                                <v-select dense outlined :items="timezones" v-model="form.values.timezone" :rules="form.rules.timezone" label="Timezone" append-icon="lock_clock"></v-select>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu v-model="form.values.startDateMenu" :close-on-content-click="false" :nudge-right="40" transition="scale-transition" offset-y min-width="auto">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense outlined v-model="form.values.startDate" :rules="form.rules.startDate" label="Start Date" append-icon="mdi-calendar" readonly v-bind="attrs" v-on="on"></v-text-field>
                                                    </template>
                                                    <v-date-picker v-model="form.values.startDate"></v-date-picker>
                                                </v-menu>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu ref="menu" v-model="startTimeMenu" :close-on-content-click="false" :nudge-right="40" :return-value.sync="form.values.startTime" transition="scale-transition" offset-y max-width="290px" min-width="290px">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense v-model="form.values.startTime" label="Start Time" append-icon="mdi-clock-time-four-outline" readonly v-bind="attrs" v-on="on" outlined></v-text-field>
                                                    </template>
                                                    <v-time-picker v-if="startTimeMenu" v-model="form.values.startTime" full-width @click:minute="$refs.menu.save(form.values.startTime)"></v-time-picker>
                                                </v-menu>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu v-model="endDateMenu" :close-on-content-click="false" :nudge-right="40" transition="scale-transition" offset-y min-width="auto">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense outlined v-model="form.values.endDate" :rules="form.rules.endDate" :min="form.values.startDate" label="End Date" append-icon="mdi-calendar" readonly v-bind="attrs" v-on="on"></v-text-field>
                                                    </template>
                                                    <v-date-picker v-model="form.values.endDate"></v-date-picker>
                                                </v-menu>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="2">
                                                <v-menu ref="menu" v-model="endTimeMenu" :close-on-content-click="false" :nudge-right="40" :return-value.sync="form.values.endTime" transition="scale-transition" offset-y max-width="290px" min-width="290px">
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-text-field dense v-model="form.values.endTime" label="End Time" append-icon="mdi-clock-time-four-outline" readonly v-bind="attrs" v-on="on" outlined></v-text-field>
                                                    </template>
                                                    <v-time-picker v-if="endTimeMenu" v-model="form.values.endTime" :min="form.values.startTime" full-width @click:minute="$refs.menu.save(form.values.endTime)"></v-time-picker>
                                                </v-menu>
                                            </v-col>
                                        </v-row>
                                    </v-form>
                                </v-card>

                                <v-btn color="primary" @click="validate()" :disabled="!valid"> Continue </v-btn>
                                <router-link :to="`/${segment1}`">
                                    <v-btn text> Cancel </v-btn>
                                </router-link>
                            </v-stepper-content>

                            <v-stepper-content step="2">
                                <v-card class="mb-12" elevation="0">
                                    <v-form ref="form2" lazy-validation v-model="valid2" id="form2">
                                        <v-row>
                                            <v-card-text class="font-weight-bold">
                                                Destination

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>The scan destination is the end point for a consumer experience. Can be single URL or use URL Groups. </span>
                                                </v-tooltip>
                                            </v-card-text>
                                        </v-row>

                                        <v-row>
                                            <v-col class="col-sm-2 col-lg-2 col-12">
                                                <v-select dense outlined :items="urlTypes" label="Single or Multi URL" v-model="form.values.urlType" :rules="form.rules.urlType"></v-select>
                                            </v-col>
                                            <v-col cols="12" sm="6" md="2">
                                                <v-text-field dense outlined v-model="form.values.url" :rules="form.rules.url" label="URL" required></v-text-field>
                                            </v-col>
                                        </v-row>

                                        <v-row>
                                            <v-card-text class="font-weight-bold"
                                                >Conditions :

                                                <v-tooltip right>
                                                    <template v-slot:activator="{ on, attrs }">
                                                        <v-btn icon v-bind="attrs" v-on="on">
                                                            <v-icon color="grey lighten-1">info</v-icon>
                                                        </v-btn>
                                                    </template>
                                                    <span>Set the conditions for a campaign. If all conditions are true, this campaign will trigger for consumer experience.</span>
                                                </v-tooltip>
                                            </v-card-text>

                                            <v-col cols="12" sm="6" md="4">
                                                <v-select dense outlined :items="attributes" item-text="name" item-value="id" v-model="form.values.attribute" :rules="form.rules.attribute" label="Attribute"></v-select>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="1">
                                                <v-combobox v-model="operator" :items="operators" item-text="operator" item-value="id" label="Operator" outlined dense></v-combobox>
                                            </v-col>

                                            <v-col cols="12" sm="6" md="4">
                                                <!-- <v-text-field dense outlined v-model="form.values.value" :rules="form.rules.value" label="Values" required></v-text-field> -->

                                                <v-text-field v-model="value" :items="values" label="Value" multiple outlined dense></v-text-field>
                                            </v-col>
                                        </v-row>
                                    </v-form>
                                </v-card>

                                <v-btn color="primary" @click="validate2()" :disabled="!valid2"> Update </v-btn>

                                <v-btn text @click="e1 = 1"> Back </v-btn>
                            </v-stepper-content>

                            <v-stepper-content step="3"> </v-stepper-content>
                        </v-stepper-items>
                    </v-stepper>
                </v-card>
            </v-col>
        </v-row>
    </v-container>
</template>

<script>
import Navbar from '../../../components/Navbar'
import Breadcrumbs from '../../../components/Breadcrumbs'
import PanelHeader from '../../../components/PanelHeader'
import axios from 'axios'
import moment from 'moment-timezone'

export default {
    components: {
        Navbar,
        Breadcrumbs,
        PanelHeader
    },
    beforeMount() {},
    computed: {
        segment1: function () {
            const firstSegment = new URL(window.location.href).pathname.split('/')[1]
            return `${firstSegment}`
        },
        timeZone: function () {
            console.log('timeZone')
        }
    },
    beforeMount() {},

    mounted() {
        this.getCampaign()
    },

    data() {
        return {
            campaign: {},
            form: {
                errors: {},
                values: {
                    name: this.campaign.name,
                    type: 'Marketing',
                    description: null,
                    timezone: 'America/New_York',
                    startDate: new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().substr(0, 10),
                    endDate: new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().substr(0, 10),
                    startTime: moment().format('HH:mm'),
                    endTime: '24:00',
                    urlType: 'Single',
                    url: 'https://',
                    attribute: '',
                    operator: '',
                    value: ''
                },
                rules: {
                    type: [(v) => !!v || 'Type is required'],
                    name: [(v) => !!v || 'Name is required'],
                    startDate: [(v) => !!v || 'Start Date is required'],
                    endDate: [(v) => !!v || 'End Date is required'],
                    timezone: [(v) => !!v || 'Timezone is required'],
                    startTime: [(v) => !!v || 'Start Time is required'],
                    endTime: [(v) => !!v || 'End Time is required'],
                    urlType: [(v) => !!v || 'URL Type is required'],
                    url: [(v) => !!v || 'URL is required'],
                    attribute: [(v) => !!v || 'Attribute is required'],
                    operator: [(v) => !!v || 'Operator is required'],
                    value: [(v) => !!v || 'Value is required']
                }
            },
            e1: 1,
            valid: false,
            valid2: false,
            types: ['Product', 'Marketing'],
            operator: [],
            operators: ['=', '!=', 'in', 'not in'],
            value: [],
            values: ['Italy', 'Finland', 'Norway'],
            timezones: moment.tz.names(),
            startDateMenu: false,
            endDateMenu: false,
            startTimeMenu: false,
            endTimeMenu: false,
            urlTypes: ['Single', 'Multiple'],
            attributes: []
        }
    },
    watch: {
        'form.values.attribute'() {
            this.operator = null
            axios.defaults.headers['Content-Type'] = 'application/json'
            let data = {
                $root: 'vc_operator',
                op: 'read',
                brand: 'COLM',
                selection: {
                    filters: [`id:${this.form.values.attribute}`]
                },
                _SESSION: localStorage.getItem('session')
            }
            axios.post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, data).then((response) => {
                this.operators = response.data.operators
            })
        }
    },
    methods: {
        getAllData(id) {
            let myForm = document.getElementById(id)
            console.log(
                Array.from(myForm.elements).map((e) => {
                    return e.value
                })
            )
        },
        validate() {
            this.$refs.form.validate()

            if (this.$refs.form.validate()) {
                let data = {
                    $root: 'vc_rule_attribute',
                    op: 'read',
                    brand: 'COLM',
                    _SESSION: localStorage.getItem('session')
                }

                axios.defaults.headers['Content-Type'] = 'applcation/json'
                axios.post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, data).then((response) => {
                    this.attributes = response.data.rule_attributes
                })
                this.e1 = 2
                console.info(this.form.values)
            } else {
                console.info(this.form.values)
            }
        },
        validate2() {
            this.$refs.form2.validate()
            if (this.$refs.form2.validate()) {
                let data = {
                    id: this.form.values.id,
                    name: this.form.values.name,
                    description: this.form.values.description,
                    start_date: this.form.values.startDate,
                    end_date: this.form.values.endDate,
                    priority: '100',
                    status_id: 1,
                    type_id: 1
                }

                let body = {
                    $root: 'vc_campaign',
                    op: 'update',
                    brand: 'COLM',
                    campaigns: [data],
                    _SESSION: localStorage.getItem('session')
                }

                // this.$store
                //  .dispatch('editCampaign', body)
                //  .then(() => {
                //      this.$router.push({
                //          path: `/campaigns`
                //      })
                //  })
                //  .catch((err) => {
                //      console.log('Something went wrong: ', err)
                //  })
            } else {
                console.info(this.form.values)
            }
        },
        displayTime(time) {
            time = time.split(':')[0]
            if (time > 12) {
                return 'PM'
            } else {
                return 'AM'
            }
        },
        getCampaign() {
            let filters = 'id:' + this.$route.params.id
            let body = {
                $root: 'vc_campaign',
                op: 'read',
                brand: 'COLM',
                selection: {
                    filters: [filters]
                },
                _SESSION: localStorage.getItem('session')
            }

            axios.defaults.headers['Content-Type'] = 'applcation/json'
            axios
                .post(`${process.env.VUE_APP_API_ENDPOINT_URL}`, body)
                .then((response) => {
                    if (response.data.status == 0) {
                        this.campaign = response.data.campaigns[0]
                    } else {
                        alert(response.data.statustext)
                        reject(response.data.statustext)
                    }
                })
                .catch((err) => {
                    console.log('Something went wrong: ', err)
                })
        }
    }
}
</script>

<style></style>

parsing out data from an object into two other objects by using an array

Trying to parse out airport data into two by using the array selected_city_codes. So airport data would be into two parts, one with only the selected city codes and the other without the city codes.

I tried to attempt this using modify_airport_data but for some reason airport_data_results is not how I wanted it to be.

What would be the best approach to this problem?

airport_data = [{"departure_time":"12:00","arrival_time":"03:00","city_id":"BOS"},  
{"departure_time" :"12:00","arrival_time":"03:00","city_id":"BOS"},
{"departure_time" :"01:00","arrival_time":"04:00","city_id":"SFO"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"DEN"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"BOS"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"SFO"}]; 

selected_city_data = [];

selected_city_codes=['BOS','SFO'];

function modify_airport_data(airport_data, selected_city_data,selected_city_codes) {
    parsed_airport_data = []; 
    var counter = 0; //for tracking purposes
    for (j=0; j < airport_data.length; j++) {
        for (i=0; i < selected_city_codes.length; i++) {
            if (airport_data[j].city_id == selected_city_codes[i]) {
                selected_city_data.push(airport_data[j]);
                counter = 0; //we reset counter during match
            }
            else{
                counter++; //and increment it if there is no match
            }
            if(counter == selected_city_codes.length) {
                parsed_airport_data.push(airport_data[j]);
            }
        }
    }
    airport_data = parsed_airport_data;
    return airport_data; 
}

airport_data_results = modify_airport_data(airport_data, selected_city_data,selected_city_codes);

Actual Results

airport_data_results = [{departure_time: '01:00',arrival_time: '04:00',city_id: 'SFO' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'DEN' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'SFO' } ]

selected_city_data = [{departure_time: '12:00',arrival_time: '03:00',city_id: 'BOS' },
{departure_time : '12:00',arrival_time: '03:00',city_id: 'BOS' },
{departure_time : '01:00',arrival_time: '04:00',city_id: 'SFO' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'BOS' },
{departure_time : '03:00',arrival_time: '05:00',city_id: 'SFO' } ]

Desired Results

airport_data_results = [{departure_time : '03:00',arrival_time: '05:00',city_id: 'DEN' }]

selected_city_data = [{"departure_time":"12:00","arrival_time":"03:00","city_id":"BOS"},  
{"departure_time" :"12:00","arrival_time":"03:00","city_id":"BOS"},
{"departure_time" :"01:00","arrival_time":"04:00","city_id":"SFO"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"BOS"},
{"departure_time" :"03:00","arrival_time":"05:00","city_id":"SFO"}]; 

JSON object array return undefined

I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element “events”, but it always return “Undefined” to me.

I’m guessing maybe it’s because events is a JSON array and I can’t directly use it in JS?

Here is my code:

function doPost(e) {
  var msg = JSON.parse(JSON.stringify(e.postData.contents));
  
  console.log(msg);
  //log succesfully

  console.log(msg.events);
  //"Undefined"
}

If I try to log the elements in the events instead of the array events itself:

  console.log(msg.events[0].replyToken);
  //"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"

The result of msg will is in below:

{
  "destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
  "events": [
    {
      "type": "message",
      "message": {
        "type": "text",
        "id": "*********",
        "text": "Hi"
      },
      "timestamp": 1642616050062,
      "source": {
        "type": "group",
        "groupId": "***********",
        "userId": "*************"
      },
      "replyToken": "************",
      "mode": "active"
    }
  ]
}

I’ve seen several similar problems for array in JS.
I tried them but all of them didn’t work, please help me.

Why event handler callback is getting executed immediately before entire call stack is executed?

Please help in explaining why the click event handler is executed before the script is finished executing.

console.log('Script started running')
document.body.addEventListener('click', () => {
  console.log('Click callback executed')
})
console.log('Before click')
document.body.click()
console.log('After click')

My expectation was

Script started running
Before click
After click
Click callback executed

But the output observed on running is

Script started running
Before click
Click callback executed
After click

Should the script not be executed fully(call stack made empty) before any event callback from the task queue is executed ?

if else statement within a function is breaking function in javascript

I am 90% finished with a simple calculator that tells you the cost difference between shopping in person vs shopping online. You can view it below. My only problem is the last sentence. It says

You should shop in person. You’ll save €x everytime you shop.

X updates fine, just try it out and see. My problem is I want to display a string. The value of the string will be determined by an if/else statement.

If (cost of shopping in person < cost of shopping online) {display the above statement with x = difference in cost} Else {You should shop online. You’ll save €x everytime you shop.}

I have included below my code, with my attempted if/else statement commented out because it breaks the code. I have tried just about everything and I’m at a roadblock. Any help would be greatly appreciated.

    var incomePerHour = document.getElementById("income_p_hour");
    var timeToShop = document.getElementById("time_to_shop");
    var deliveryCharge = document.getElementById("delivery_charge");
    var timeToDeliver = document.getElementById("time_to_deliver");

    var inPersonElement = document.getElementById("inPersonCost");
    var deliveryElement = document.getElementById("deliveryCost");
    var summaryElement = document.getElementById("summary");
  //  var summaryFullElement = document.getElementById("summaryFull")

    var inPersonTextElement = document.getElementById("inPersonCostText");
    var deliveryTextElement = document.getElementById("deliveryCostText");
    var summaryTextElement = document.getElementById("summaryText");
    //var summaryFullTextElement = document.getElementById("summaryFullText");



    function updateProfit() {
      var inPersonCost = ((Number(incomePerHour.value)/60) * Number(timeToShop.value)).toFixed(2);
      var deliveryCost = (((Number(incomePerHour.value)/60) * Number(timeToDeliver.value)) + Number(deliveryCharge.value)).toFixed(2);
      var summary = (inPersonCost - deliveryCost).toFixed(2);
    /*  var summaryFull = (if ((parseInt(summary)) > 0){
        "You should shop online. You will save" + summary + "everytime you shop.";
      } else {
        "You should shop in person. You will save" + (summary * -1) + "everytime you shop.";
      })*/
      inPersonElement.value = inPersonCost;
      deliveryElement.value = deliveryCost;
      summaryElement.value = summary;
      //summaryFullElement.value = summaryFull;

      inPersonTextElement.innerText = inPersonCost;
      deliveryTextElement.innerText = deliveryCost;
      summaryTextElement.innerText = summary;
    //  summaryFullTextElement.innerText = summaryFull;

    }

    incomePerHour.onchange = timeToShop.onchange = deliveryCharge.onchange = timeToDeliver.onchange = updateProfit;
    <form method="POST">
      How much do you value your time per hour? <input type="int" id="income_p_hour"> <br />
      How much of your time does it take to go grocery shopping in person in minutes? <input type="int" id="time_to_shop"> <br />
      How much is the delivery charge? <input type="int" id="delivery_charge"> <br />
      How much of your time does it take to order your groceries online in minutes? <input type="int" id="time_to_deliver"> <br />

  <!--  <input type="hidden" id="profit" name="profit"/>
   Profit: $<span id="profitText"></span> -->
<br>
    <input type="hidden" id="inPersonCost" name="inPersonCost"/>
    Cost of shopping in person: <span id="inPersonCostText"></span> <br />
    <input type="hidden" id="deliveryCost" name="deliveryCost"/>
    Cost of shopping online: <span id="deliveryCostText"></span>
<br>
You should shop in person. You'll save €<input type="hidden" id="summary" name="summary"/><span id="summaryText"></span> everytime you shop.
<br>
<!-- <input type="hidden" id="summaryFull" name="summaryFull"/><span id="summaryFullText"></span> -->
    </form>