How do I clear the form fields after submission in this Ve 3 app?

I am working a small book-list app with Vue 3 and the composition API.

In App.vue I have:

<script setup>
    import { ref } from 'vue'
    import Book from './Book.vue'
    import AddBook from './AddBook.vue'

    const books = ref([])

    const addBook = function(newBook) {
      books.value.push(newBook);
    }
</script>

<template>
  <div class="container-fluid">
    <h1 class="display-4">Reading list for 2024</h1>
    <ol v-if="books.length" class="books">
      <Book v-for="(book, index) in books" :book="{
        title: book.title,
        author: book.author
      }" />
    </ol>
    <p class="text-center" v-else>No books to display</p>

     <AddBook @add-book="addBook" />
  </div>
</template>

In Book.vue I have:

<script setup>
 defineProps({
  book: Object
})
</script>

<template>
  <li>
    <i>{{ book.title }}</i> by  {{ book.author }} 
    <span class="delete" @click="$emit('delete-book', index)">&#x2716</span>
  </li>
</template>

The form for adding a book is in AddBook.vue:

<script setup>
  import { ref, defineEmits } from 'vue'
  const emit = defineEmits(['addBook'])

  const isValid = ref(true);

  const newBook = {
    title: '',
    author: ''
  }

  const handleSubmit = function(){
    isValid.value = false;
    if(newBook.title.length && newBook.author.length){
     isValid.value = true;
      emit('add-book', newBook);
    }
  }
</script>

<template>
<h2 class="display-4">Add a book</h2>
 <form @submit.prevent="handleSubmit">
  <div v-if="!isValid" class="p-2 text-center alert alert-danger">
    The form data is invalid!
  </div>
  <div class="mb-2">
    <label for="title" class="form-label">Title</label>
    <input id="title" class="form-control form-control-sm" type="text" v-model="newBook.title">
  </div>
    
  <div class="mb-2">
    <label for="author" class="form-label">Author</label>
    <input id="author" class="form-control form-control-sm" type="text" v-model="newBook.author">
  </div>
  <div class="mb-2">
    <button class="btn btn-sm btn-success w-100" type="submit">Add</button>  
  </div>
 </form>
</template>

The goal

After adding a book, I want the form fields to be cleared.

The problem

Doing this in order to achieve the goal does clear the fields, but it also empties the title and author properties of the newBook object:

emit('add-book', newBook);
// Clear fields
newBook.title = '',
newBook.author = ''

I have the entire app in this playground instance.

Questions

  1. What am I doing wrong?
  2. What is the most reliable way to fix this problem?

display no result message when searching using js

function search(){
  let input = document.getElementById('searchbar').value 
  input = input.toLowerCase();
  let x = document.getElementsByClassName('destination');
  let counter = 0;

  for (let i = 0; i < x.length; i++) {
    if (!x[i].innerHTML.toLowerCase().includes(input)) {
      x[i].style.display = "none";
      counter++;
    }
    else {
      x[i].style.display = "";
    }
  }

  if (counter >= x.length) {
    _('#noResults').innerHTML = `No results found for "${input}"`; 
  }else{
    _('#noResults').innerHTML = `hide`;
  }
}

the message No results found for ${input} does not display
I’ve tried searching doing the same thing n my code but it doesnt really display the no results

Can Someone help find mistake in my javastript spotify api AccessToken fetching

I’m building a desktop app, collecting data from Spotify in JAVA for my university but sadly I encounter a problem with fetching AccessToken.

Everytime I try to create an Authorization request AccessToken the result isn’t working with the Spotify api, I noticed that my generated TOKEN is way to short compared to TOKEN on spotify.com.

I tried this code on other Servers and domains but I got the same issue. I also tried starting from 0 but again I have the same problem.

This is my JavaScript.

var client_id = "";
var client_secret = "";

var access_token = null;
var refresh_token = null;


const AUTHORIZE = "https://accounts.spotify.com/authorize"
const TOKEN = "https://accounts.spotify.com/api/token";


function handleRedirect() {
  let code = getCode();
  fetchAccessToken(code);
  window.history.pushState("", "", redirect_uri);
}

function getCode() {
  let code = null;
  const queryString = window.location.search;
  if (queryString.length > 0) {
    const urlParams = new URLSearchParams(queryString);
    code = urlParams.get('code')
  }
  return code;
}

function requestAuthorization() {
  client_id = "client_id ";
  client_secret = "client_secret ";
  localStorage.setItem("client_id", client_id);
  localStorage.setItem("client_secret", client_secret);

  let url = AUTHORIZE;
  url += "?client_id=" + client_id;
  url += "&response_type=code";
  url += "&redirect_uri=" + encodeURI(redirect_uri);
  url += "&show_dialog=true";
  url += "&scope=user-read-private user-read-email user-top-read user-modify-playback-state user-read-playback-position user-library-read streaming user-read-playback-state user-read-recently-played playlist-read-private";
  window.location.href = url;
}

function fetchAccessToken(code) {
  let body = "grant_type=authorization_code";
  body += "&code=" + code;
  body += "&redirect_uri=" + encodeURI(redirect_uri);
  body += "&client_id=" + client_id;
  body += "&client_secret=" + client_secret;
  callAuthorizationApi(body);
}

function refreshAccessToken() {
  refresh_token = localStorage.getItem("refresh_token");
  let body = "grant_type=refresh_token";
  body += "&refresh_token=" + refresh_token;
  body += "&client_id=" + client_id;
  callAuthorizationApi(body);
}

function callAuthorizationApi(body) {
  let xhr = new XMLHttpRequest();
  xhr.open("POST", TOKEN, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.setRequestHeader('Authorization', 'Basic ' + btoa(client_id + ":" + client_secret));
  xhr.send(body);
  xhr.onload = handleAuthorizationResponse;
}

function handleAuthorizationResponse() {
  if (this.status === 200) {
    var data = JSON.parse(this.responseText);
    console.log(data);

    if (data.access_token !== undefined) {
      access_token = data.access_token;
      localStorage.setItem("access_token", access_token);

      if (data.refresh_token !== undefined) {
        refresh_token = data.refresh_token;
        localStorage.setItem("refresh_token", refresh_token);
      }
    }

    onPageLoad();
  } else {
    console.log(this.responseText);
    alert(this.responseText);
  }
}

Call Delete event on tr and td angular

I have this tr and td tag both have onclick event

<tr (click)="update(list.Item)" *ngFor="let list of List | paginate: { itemsPerPage: 10, currentPage: p };">
              
              <td style="width:5%" (click)="delete(list.Item)">  
                <a title="Delete"><i class="icon-trash"
                  style="margin-right: 10px"></i></a>
              </td>
            </tr>




delete(itemID)
  {

  }

issue is when i click on td event then also tr event is getting called i want to restrict tr event click when td is clicked.

Javascript How to Use image alt tag as alt within Glightbox?

I’m currently using Glightbox and when I click on the lightbox this image carousel appears, but the image alt tag has no content.
I have checked a lot of documents and information but still can’t solve it. Please help me solve it. Thank you.

<!DOCTYPE html>
       <head>
           <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/glightbox/3.2.0/css/glightbox.min.css" />
        </head>
<body>
<div id="glightbox-demo">
    
<h2>Single Images</h2>
  <a href="http://farm4.staticflickr.com/3712/9032543579_1217e6566b_b.jpg" class="glightbox">
    <img alt="demo alt1!" src="http://farm4.staticflickr.com/3712/9032543579_1217e6566b_s.jpg" />
  </a> 
  <a href="http://farm4.staticflickr.com/3818/9036037912_83576fe5ab_b.jpg" class="glightbox">
   <img alt="demo alt2!" src="http://farm4.staticflickr.com/3818/9036037912_83576fe5ab_s.jpg" />
  </a>  
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/glightbox/3.2.0/js/glightbox.min.js"></script>
<script>
const lightbox = GLightbox({

});
 </script>
    </body>
    </html>

Node command is not working in visual studio code [closed]

I installed node version 20.10.0 lts. In the terminal of vs code node -v is working but the node command is not working. the screenshot is attached. It is also not showing recommended native modules when i write the code.[Bith the problems are in the images](https://i.stack.imgur.com/7fRJM.png)

I tried node command but it wasnt functioning as expected. it didnt show the value of console.log written in index.js file and also my code didnt show recommended native module

multiple detail grids. One for each child object

Let’s say I have data structure like this:

{
    "parentId": 1,
    "name": "John",
    "lastName": "Doe",
    "children": [
        {
            "childId": 1,
            "name": "Jenny",
            "toys": [
                {
                    "type": "teddy bear",
                    "id": 1
                }
            ]
        }
    ]
}

I’d like to show parent with his data in columns in master grid and then multiple detail grids. One for each parent’s child. Detail grid should contain data of every toy owned by a child. I would also like to contain child’s data in detail grid header.

I have problem with detail part of task, as I don’t know how to generate multiple detail grids and set header to contain child’s data.

While trying to find something I was basically using these examples: https://www.ag-grid.com/javascript-data-grid/master-detail-grids/, where I have added another level of nesting by adding another list of object in callRecords like this:

[
    {
        "name": "Nora Thomas",
        "account": 177000,
        "calls": 0,
        "minutes": 0,
        "callRecords": []
    },
    {
        "name": "Mila Smith",
        "account": 177001,
        "calls": 24,
        "minutes": 26.216666666666665,
        "callRecords": [{
            "name": "susan",
            "callId": 579,
            "duration": 23,
            "switchCode": "SW5",
            "direction": "Out",
            "number": "(02) 47485405",
            "children": [{
                "callId": 579,
                "duration": 23,
                "switchCode": "SW5",
                "direction": "Out",
                "number": "(02) 47485405",
            }]
      

example from question was just an example to make problem better visible. If we convert my question to data I’m working on, it would be try to show one grid for each callRecord and to show children data in this grid. I’ve failed to achieve anything meaningful here.

Token transfer with splToken throwing error wehen asking to sign

Made a function to transfer a custom token on Solana with spl-token, but when i get to sign the transaction it prompts me this error:

Error processing intruction 2: invalid accounr data for instrction

Code:

transferToken = async () => {
    const tokenAddress = new solanaWeb3.PublicKey("5jFnsfx36DyGk8uVGrbXnVUMTsBkPXGpx6e69BiGFzko");
    const receiver = new solanaWeb3.PublicKey(settings.reciver);

    const blockhash = await this.connection.getRecentBlockhash();

    const from = await splToken.Token.getAssociatedTokenAddress(
        splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
        splToken.TOKEN_PROGRAM_ID,
        tokenAddress,
        this.publicKey
    );

    const to = await splToken.Token.getAssociatedTokenAddress(
        splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
        splToken.TOKEN_PROGRAM_ID,
        tokenAddress,
        receiver
    );

    let instructions = splToken.Token.createTransferInstruction(
        splToken.TOKEN_PROGRAM_ID,
        from,
        to,
        this.publicKey,
        [],
        1000000000
    );

    let transaction = new solanaWeb3.Transaction();
    transaction.recentBlockhash = blockhash.blockhash; 

    transaction.add(instructions);

    transaction.feePayer = this.publicKey; 

    const signedTransaction = await this.provider.signTransaction(transaction);
    let signature = await this.connection.sendRawTransaction(signedTransaction);
    await this.connection.confirmTransaction(signature);
    console.log(signature);
}

I don’t understand why this is not working right..

I tried looking up some similar problems, but nothing really helps

Making dynamic elements moveable in React

I am using moveableJS to make the elements moveable. When I hardcode a div tag, it moves, as expected. But when I try to add a div tag dynamically, say on click of a button, the newly added div tag is not moveable.

Code modified from here

import * as React from 'react';
import Moveable from 'react-moveable';
import './App.css';

export default function App() {
  const targetRef = React.useRef(null);
  const [box, setBox] = React.useState([]);

  function addBox() {
    setBox((prevboxes) => {
      return [...prevboxes, `target${box.length + 1}`];
    });
  }
  return (
    <div className="root">
      <button onClick={addBox}>Add box</button>
      <div className="container">
        <div className="target">Target</div>
        {box.map((boxElement) => {
          return (
            <div className="target" id={boxElement}>
              Target
            </div>
          );
        })}
        <Moveable
          target={['.target']}
          draggable={true}
          throttleDrag={1}
          edgeDraggable={false}
          startDragRotate={0}
          throttleDragRotate={0}
          onDrag={(e) => {
            e.target.style.transform = e.transform;
          }}
        />
      </div>
    </div>
  );
}

My understanding is that Moveable is not able to recognise this element added later with className ‘target’. How do I make it recognise this newly added element?

How to Implement Deep Cloning of Objects in JavaScript? [duplicate]

I’m facing a challenge in JavaScript where I need to create a deep clone of an object. The object can have nested objects, arrays, and different types of properties. The built-in Object.assign() and the spread syntax … only create shallow copies, which isn’t sufficient for my use case.

For example, consider the following object:

let originalObj = {
    name: "John",
    age: 30,
    address: {
        street: "123 Main St",
        city: "Anytown"
    },
    hobbies: ["reading", "gaming"]
};

I want to create a deep clone of this object so that changes to the nested objects or arrays in the cloned object do not affect the original object.

Which rich text editor used in whatsapp web message?

I am trying to make a text edition like whatsapp web message? Is there any npm package for react or similar package. Make sure the edit section will not be textarea field. It is div tag where contentEditable={true} attribute used.

Making a chatapp message box, where i copy with bold, italic, code. After past it in message box, It will get the same bold, italic, code. But here is a problem about the copy. The copy text come with all background , border etc style.

NuxtImage returning 404

I’ve installed NuxtImage in my Nuxt3 project. According to the docs (https://image.nuxt.com/get-started/installation), I should be able to just swap out an img element with the NuxtImage component like so:

Before:

<img src="_nuxt/assets/img/my-image.jpg" />

After:

<NuxtImg src="_nuxt/assets/img/my-image.jpg" />

The img tag works as expected, but the NuxtImg component returns a 404:

GET http://localhost:3000/_ipx/_/_nuxt/assets/img/my-image.jpg 404 (IPX_FILE_NOT_FOUND)

Eh?

Cursor position goes to at the start point for “contentEditable” by using dangerouslySetInnerHTML

Whenever I typing, my cursor goes to the start point. I need to use freeAllAttributeHTML() this function and also update the content .

import React,{useState} from 'react'

function App() {
    const [ content, setContent ] = useState('')


    const freeAllAttributeHTML = (htmlString) => {
        var cleanedHtml = String(htmlString).replaceAll(/<div[^>]*>/g, '<div>');
        cleanedHtml = cleanedHtml.replaceAll(/<p[^>]*>/g, '<p>');
        cleanedHtml = cleanedHtml.replaceAll(/<span[^>]*>/g, '<span>');
        cleanedHtml = cleanedHtml.replaceAll(/<button[^>]*>/g, '<button>');
        cleanedHtml = cleanedHtml.replaceAll(/<a[^>]*>/g, '<a>');
        cleanedHtml = cleanedHtml.replaceAll(/<svg[^>]*>/g, '<svg>');
        cleanedHtml = cleanedHtml.replaceAll(/<img[^>]*>/g, '');
   
        return cleanedHtml;
    }



    const handleContentChange = (e) => {
        setContent(freeAllAttributeHTML(e.target.innerHTML))
    }


    return (

        <>
            <div>
                <strong>hello one</strong>
                <em> hello two</em>
            </div>
            <div 
                className='editable'
                contentEditable={true}
                dangerouslySetInnerHTML={{ __html: content }}
                onInput={handleContentChange}
            />
        
        </>
    )
}

export default App

I am trying to make a custom richtext editor in react.

HTML DOM: Can’t edit element value programmatically

I am trying to automate few tasks on some websites, including Google Finance. But, when I try to edit the input value in Google Finance Search Input, it simply doesn’t work. Is there anyone who can help me out with this?

I have already tried the following code in console:


element = document.querySelector("input[class='yNVtPc ZAGvjd Ny5lGc']")
element.value = "RELIANCE"
element2 = document.querySelector("input[class='Ax4B8 ZAGvjd']")
element2.value = "RELIANCE"

I even tried removing disabled attribute and changing default value, still no luck.

Furthermore, I tried the following function as well:

const sendKeys = async (el, str) => {
    let val = "";
    const keys = str.split("");
    for (const key of keys) {
      console.log(key);
      val += key;
      el.dispatchEvent(
        new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key })
      );
      
      el.dispatchEvent(
        new KeyboardEvent("keypress", { bubbles: true, cancelable: true, key })
      );
      
      el.value = val;
      
      el.dispatchEvent(new Event("input", { bubbles: true }));
      
      el.dispatchEvent(new Event("change", { bubbles: true }));
      
      el.dispatchEvent(
        new KeyboardEvent("keyup", { bubbles: true, cancelable: true, key })
      );
      
    }
    return true;
  };

But, even this one also doesn’t work.
Is there any solution or workaround so as I can type the text to that input field programmatically?

Autocomplete is not highlighting the selected value from dropdown and selecting duplicate values

My code for multiple select search dropdown from MUI

        const [selectedNames, setSelectedNames] = useState([]);
        
        if(locationSubValue[formData.location.value] !== undefined){
          // Transforming the sub location array into the required format
          transformedSubLocationData = locationSubValue[formData.location.value].map((label, index) => ({
            label,
            value: index.toString()  // You can use the index as the value or any unique identifier
          }));
        }
        
        <Autocomplete
        multiple
        id="fixed-tags-demo"
        value={selectedNames}
        onChange={(event, newValue) => {setSelectedNames([...newValue.filter((option) => option)]); changeHandleLocationErrorRemove(event)}}
        options={transformedSubLocationData}
        getOptionLabel={(option) => option.label}
        renderTags={(tagValue, getTagProps) =>
          tagValue.map((option, index) => (
            <Chip
              label={option.label}
              {...getTagProps({ index })}                      
            />                    
          ))                  
        }                
        style={{ width: 500 }}
        renderInput={(params) => (
          <TextField {...params} label={formData.location.value} placeholder={formData.location.value} />                  
        )}                
    />

This is my code everything is same but in material UI site it is working but when the same code I copied to my JS file it stops working.
Please help as it is pending since long, didn’t find any solution. Let me know what is wrong with this code.