Create text by checking radios

I want to create some text in a contentediable by checking radios (without pressing a button at the end). I’ve created this but don’t understand why it doesn’t work :/

I guess there is a problem with the function’s argument but I can’t figure out why.

Thanks if you help me 🙂

function genereItem(x){
    document.getElementById("item"+x).innerHTML = document.querySelector("input[name="+x+"]:checked").value;
}
.editable{
 border: solid black 1px;
}
<div>
  <div>itemA1
    <input id="yesA1" name="A1" type="radio" value="item A1 = yes," onchange="genereItem(A1)"/>
    <label for="yesA1">yes</label>
    <input id="noA1" name="A1" type="radio" value="item A1 = no," onchange="genereItem(A1)"/>
    <label for="noA1">no</label>
    <input id="NTA1" name="A1" type="radio" value="item A1 = NT," checked="checked" onchange="genereItem(A1)"/>
    <label for="NTA1">NT</label>
  </div>
  <div>itemA2
    <input id="yesA2" name="A2" type="radio" value="item A2 = yes." onchange="genereItem(A2)"/>
    <label for="yesA2">yes</label>
    <input id="noA2" name="A2" type="radio" value="item A2 = no." onchange="genereItem(A2)"/>
    <label for="noA2">no</label>
    <input id="NTA2" name="A2" type="radio" value="item A2 = NT." checked="checked" onchange="genereItem(A2)"/>
    <label for="NTA2">NT</label>
  </div>
  <div>itemB1
    <input id="yesB1" name="B1" type="radio" value="item B1 = yes," onchange="genereItem(B1)"/>
    <label for="yesB1">yes</label>
    <input id="noB1" name="B1" type="radio" value="item B1 = no," onchange="genereItem(B1)"/>
    <label for="noB1">no</label>
    <input id="NTB1" name="B1" type="radio" value="item B1 = NT," checked="checked" onchange="genereItem(B1)"/>
    <label for="NTB1">NT</label>
  </div>
  <div>itemB2
    <input id="yesB2" name="B2" type="radio" value="item B2 = yes." onchange="genereItem(B2)"/>
    <label for="yesB2">yes</label>
    <input id="noB2" name="B2" type="radio" value="item B2 = no." onchange="genereItem(B2)"/>
    <label for="noB2">no</label>
    <input id="NTB2" name="B2" type="radio" value="item B2 = NT." checked="checked" onchange="genereItem(B2)"/>
    <label for="NTB2">NT</label>
  </div>
  <div class="editable" contenteditable="true">
    <div>
      <string id="itemA1"></string>
      <string id="itemA2"></string>
      <p/>
    </div>
    <div>
      <string id="itemB1"></string>
      <string id="itemB2"></string>
      <p/>
    </div>
  </div>
 </div>

JSON POST Payload isn’t written to file

Trying to make a simple post request to a JSON file.

I’m currently running Microsoft’s “Live Preview” extension for VS Code to run my own local http server. In the root directory I have a JSON file that I want to post to.

It posts fine but doesn’t actually write to the JSON file. Any help would be appriciated.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Test</h1>
    <label for="name" id="name">Name</label>
    <input type="text"></input>
    <button id="button">fetch</button>
    <button id="post">post</button>
    <script src="js.js"></script>
</body>
</html>

JS

var btn = document.getElementById("button");
var postBtn = document.getElementById("post");

function fetchData() {
fetch('http://127.0.0.1:3000/test.json')
  .then(response => response.json())
  .then(data => console.log(data))
}

function postData() {
    const data = {id: 4};
    fetch("http://127.0.0.1:3000/test.json", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
      
        //make sure to serialize your JSON body
        body: JSON.stringify(data)
      })
      .then( (response) => { 
         //do something awesome that makes the world a better place
      });
}

btn.addEventListener('click', () => fetchData());
postBtn.addEventListener('click', () => postData());

Can’t populate a table in html

I can’t populate the table in HTML plus im getting the following error message:

ReferenceError: document is not defined
at construirTabla (c:UsersEmiliDocumentsmaster-code-g14a-main3-Computer
Science4-TrabajoFinaljstempCodeRunnerFile.js:98:15)
at Object. (c:UsersEmiliDocumentsmaster-code-g14a-main3-Computer
Science4-TrabajoFinaljstempCodeRunnerFile.js:95:2)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47

let starWars = [
    {
        "name": "Luke Skywalker",
        "height": "172",
        "mass": "77",
        "hair_color": "blond",
        "skin_color": "fair",
        "eye_color": "blue",
        "gender": "male",
    },
    {
        "name": "C-3PO",
        "height": "167",
        "mass": "75",
        "hair_color": "n/a",
        "skin_color": "gold",
        "eye_color": "yellow",
        "gender": "n/a",
    },
    {
        "name": "R2-D2",
        "height": "96",
        "mass": "32",
        "hair_color": "n/a",
        "skin_color": "white, blue",
        "eye_color": "red",
        "gender": "n/a",
    },
    {
        "name": "Darth Vader",
        "height": "202",
        "mass": "136",
        "hair_color": "none",
        "skin_color": "white",
        "eye_color": "yellow",
        "gender": "male",
    },
    {
        "name": "Leia Organa",
        "height": "150",
        "mass": "49",
        "hair_color": "brown",
        "skin_color": "light",
        "eye_color": "brown",
        "gender": "female",
    },
    {
        "name": "Owen Lars",
        "height": "178",
        "mass": "120",
        "hair_color": "brown, grey",
        "skin_color": "light",
        "eye_color": "blue",
        "gender": "male",
    },
    {
        "name": "Beru Whitesun lars",
        "height": "165",
        "mass": "75",
        "hair_color": "brown",
        "skin_color": "light",
        "eye_color": "blue",
        "gender": "female",
    },
    {
        "name": "R5-D4",
        "height": "97",
        "mass": "32",
        "hair_color": "n/a",
        "skin_color": "white, red",
        "eye_color": "red",
        "gender": "n/a",
    },
    {
        "name": "Biggs Darklighter",
        "height": "183",
        "mass": "84",
        "hair_color": "black",
        "skin_color": "light",
        "eye_color": "brown",
        "gender": "male",
    },
    {
        "name": "Obi-Wan Kenobi",
        "height": "182",
        "mass": "77",
        "hair_color": "auburn, white",
        "skin_color": "fair",
        "eye_color": "blue-gray",
        "gender": "male",
    }
]
    
    //Popular tabla 
    construirTabla(starWars)

    function construirTabla(data) {
        let table = document.getElementById('starWars')

        for (let i = 0; i < data.length; i++) {
            let row = `<tr>
                            <td>${data[i].name}</td>
                            <td>${data[i].height}</td>
                            <td>${data[i].mass}</td>
                            <td>${data[i].hair_color}</td>
                            <td>${data[i].skin_color}</td>
                            <td>${data[i].eye_color}</td>
                            <td>${data[i].gender}</td>
                    </tr>`
            table.innerHTML + row
        }
    }
th { 
color:#fff;
}
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tablas desordenadas y ordenadas </title>

    <link rel="stylesheet" href="css/style.css">
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <table class="table table-striped">
        <tr  class="bg-info">
            <th>Nombre</th>
            <th>Estatura</th>
            <th>Masa</th>
            <th>Color de pelo</th>
            <th>Color de Piel</th>
            <th>Color Ojos</th>
            <th>Genero</th>
        </tr>
        
        <tbody id="starWars">
            
        </tbody>
    </table>
</body>

<script src="js/index.js"></script>

Updating Django profile returns not authorized error

I would like to update an existing Django profile but getting the error message:

PUT http://127.0.0.1:8000/update_profile/ 401 (Unauthorized)

The specific network error I am getting is:

detail: "Authentication credentials were not provided."

This is what the event listener triggered when my update profile button is clicked:

const handleSubmit = e => {
            e.preventDefault();
            console.log('handle submit',profileUser)
            const updatedProfileInfo = {
                username: profileUser.username,
                email: profileUser.email,
                first_name: profileUser.first_name,
                last_name: profileUser.last_name,
                city: profileUser.city,
                country: profileUser.country
            }
            console.log(updateProfile)
            updateProfile(updatedProfileInfo);
    }

updateProfile is destructured from useContext here:

let { user,logOutUser, updateProfile } = useContext(AuthContext)

here is the updateProfile function:

const updateProfile = (userData) => {
    axios
        .put('http://127.0.0.1:8000/update_profile/', {
            headers: {
                Authorization: "Bearer" + window.localStorage.getItem('authTokens').access,
                'Accept' : 'application/json',
                'Content-Type': 'application/json'
            },
            body: userData
            })
        .then(res => {
            console.log(res)
        })
}

I pass updateProfile to my Profile through ContextData:

let contextData = {
        user:user,
        loginUser:loginUser,
        logOutUser:logOutUser,
        updateToken: updateToken,
        updateProfile: updateProfile
    }
...
return(
        <AuthContext.Provider value={contextData} >
            {children}
        </AuthContext.Provider>
    )

This is how my access token is stored in localStorage
authTokens: {"access":****,"refresh":*****}

Pass value of input to other input without onclick

I have a working code to pass value from one id to another, but to do that I need a button to pass it onclick. I want to pass the value without a button directly to the other input.
As I did my research i just saw onclick solutions..
Is there any other way or am I stuck with this option

My Code:

window.onload = function() {
    document.getElementById('button').onclick = function() {
        document.getElementById('email2').value = document.getElementById('email').value;
        document.getElementById('firma2').value = document.getElementById('firma').value;
        document.getElementById('name2').value = document.getElementById('name').value;
        document.getElementById('nummer2').value = document.getElementById('nummer').value;

    }
};

I tried to make a function instead

Rendering JSX inside for loop

I have the following array:

0: {element: 'came', frequency: 3}
1: {element: 'here', frequency: 2}
2: {element: 'i', frequency: 1}

Each element is an object that shows the frequency of words in a text.

I want to do something like “The most frequent word was X, for Y times. The second most frequent word was Z, for D times.

So i did this.
textObj is the array with the objects.

function Result() {
    const results = [];
    if (textObj.length != 0) {
      for (let i = 0; i < textObj.length; i += 2) {
        results.push(
          <div>
            <h1>Most frequent word was:</h1>
            <h2>
              '{textObj[i].element}' for {textObj[i].frequency} times
            </h2>
            <h1>Second most frequent word was:</h1>
            <h2>
              '{textObj[i++].element}' for {textObj[i++].frequency} times
            </h2>
          </div>
        );
      }

      return results;
    }

    return <div></div>;
  }

And then i render it returning in the main component.

In the above example, i have the phrase “I came came came here here”. For some reason, it’s showing only the word “came” in both . But the frequency part is correct, it’s showing 3 and then 2. I tried instead of textObj[i++], textObj[i+1], but it says that cannot read ‘element’.

What am i doing wrong?

How to get window.document from selenium driver?

I have a selenium driver object. But I need DOM object how to get window.document?

I tried my covering pageSource to DOM object but it’s not working as expected.

let driver = new Builder().forBrowser("chrome").build();
driver.manage().window().maximize();

How to get window.document object from driver ?

How to pass props from one component to another in Nuxtjs

I have my index.vue inside the page folder and i am trying to loop all the category gotten from the api so i did this.

<template>
<div>
<Header :category="category"/>
</div>
</template>
<script>
export default{
import Header from '@/components/Front/Header'
name: 'MainSite',
  props: ['category', 'name'],
components:{
    Header,
  },
data: () => ({
    frontpage: [],
    category: []
  }),
  async fetch() {
    const response = await this.$axios.get('/api/frontpage')
    this.frontpage = response.data.posts
    this.category = response.data.cat
  },
}
</script>

I have the Header.vue as this which contains the navigation link i want to loop through

<template>
<div class="collapse navbar-collapse">
                    <!-- menus -->
                    <ul class="navbar-nav mr-auto">
                        <li class="nav-item active">
                            <NuxtLink class="nav-link" to="/">Home</NuxtLink>
                        </li>
                        <li class="nav-item" v-for="(cat, i) in category" :key="i.name">
                            <NuxtLink class="nav-link" :to="'/category/' + cat.slug">{{ cat.name }}</NuxtLink>
                        </li>
            <template v-if="$auth.user">
              <li class="nav-item">
                              <a class="nav-link" href="/dashboard">Admin</a>
                          </li>
            </template>
                    </ul>
                </div>
</template>
<script>
export default {
    name: 'Header',
    props: ['category', 'name'],
    
}
</script>

I keep getting this error Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "category" and also this error client.js?06a0:57 [Vue warn]: The data property "category" is already declared as a prop. Use prop default value instead.

Anytime i reload the browser the links gets displayed and the disappears with those errors above
and this also

 Parent:<li class="nav-item" data-v-383d0eae=""><a href="/category/video" class="nav-link" data-v-383d0eae="">Video</a></li>

OnMount fetch works for one component but not the other in Svelte

Using onMount to fetch my data from my API, I’m able to pass the data to a component, which then passes it to 2 other components. One of those 2 components works and is able to iterate through the data. The other one throws a “Uncaught (in promise) TypeError: Cannot convert undefined or null to object” error.

The onMount component:

<script>
    import { onMount } from "svelte";
    import TableFull from "../components/table/TableFull.svelte";

    let plants = [];
    
    onMount(async () => {
        const response = await fetch("/api/plants");
        const { data } = await response.json();
        plants = data;
    });

</script>

<main>
    <TableFull objects={plants} />
</main>

The TableFull component:

<script>
    import TableHead from "./TableHead.svelte";
    import TableRow from "./TableRow.svelte";

    export let objects;
</script>


<table>
    <TableHead object={objects[0]} />

    {#each objects as object (object.id)}
        <TableRow object={object}/>
    {/each}
</table>

Here, it is able to iterate through the objects to create TableRows, but the TableHead throws the error.

Not sure why, since they’re using the same variable. Any ideas?

Calculating Client Side HTTP Request Header Value

A website sets a custom http header with custom value for every http request(XHR) it sends. I am trying to figure out how the client side is calculating that value.

Since, the underlying javascript is responsible for calculating the value of that header, theoretically it should not be difficult. But I do lack experience debugging javascript and the code looks cryptic for me to understand anything (may be its minified). How do I approach this?

Thankyou!

Hidden navbar until Scroll Y react

I have a navbar component and want to create an effect where the background is transparent by default until the users scrolls down, giving the navbar a background. I have achieved this event with scroll listeners before but wasnt sure if there was a better React method.

Heres the component:

import * as React from 'react';
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Squash as Hamburger } from 'hamburger-react';

const links = [
  {name: "Home", path: "/"},
  {name: "Projects", path: "/projects"},
  {name: "Contact", path: "/contact"}
];

export default function Header() {
  //State to toggle navlinks
  const [isOpen, setOpen] = useState(false);

  return (
    <nav className="w-full shadow-lg bg-quaternary fixed py-2 px-3 flex justify-between items-center">
      <Link to="/">
        <div className="bg-[url('../public/images/logo.jpg')] hover:bg-[url('../public/images/logo-hover.jpg')] w-[260px] h-[60px]"></div>
      </Link>
      <div className="flex">
        <div className="lg:hidden">
          <Hamburger
            color="#ffffff"
            easing="ease-in-out"
            rounded
            toggled={isOpen}
            toggle={setOpen}
          />
        </div>

        {isOpen && (
          <ul className="h-56 bg-quaternary lg:h-auto flex flex-col lg:flex-row absolute lg:relative mt-10 lg:mt-0 right-0 lg:right-auto px-10 lg:px-0 rounded-lg lg:rounded-none shadow-sm lg:shadow-none">
            {links.map((link) => (
              <li className="m-5 lg:my-0 lg:mx-5">
                <Link className="text-2xl font-medium text-white hover:text-primary transition duration-300 ease-in-out" to={link.path}>
                  {link.name}
                </Link>
              </li>
            ))}
          </ul>
        )}

        <ul className= "h-56 bg-quaternary lg:h-auto hidden lg:flex flex-col lg:flex-row absolute lg:relative mt-10 lg:mt-0 right-0 lg:right-auto px-10 lg:px-0 rounded-lg lg:rounded-none shadow-sm lg:shadow-none">
          {links.map((link) => (
            <li className="m-5 lg:my-0 lg:mx-5">
              <Link className="text-2xl font-medium text-white hover:text-primary transition duration-300 ease-in-out" to={link.path}>
                {link.name}
              </Link>
            </li>
          ))}
        </ul>
      </div>
    </nav>
  );
}

Heres how I want the navbar by default:

enter image description here

And then when the user scrolls:

enter image description here

React ag-grid grouping collapses whenever row gets updated

I am feeding data to ag-grid via redux state. I have a button in each row using which I can update the specific row data. When I update, API is called and newly updated data will come from API and it is updated in redux state which in turn gets updated in Grid.

I am achieving this using the deltaRowDataMode. This deltaRowDataMode will only update specific row data. Data update is working fine. But when I group a column, expand the rows and then update a row data, ag-grid collapsing the grouping, though update is happening fine. For sorting, filtering it is working beautifully.

I tried rememberGroupStateWhenNewData, it is not working. I check many functionalities like expandAll, etc., but none of them suits my condition. Is there any build in functionality or approach which prevents AG-Grid from collapsing the grouping when update happens?

Unfortunately, I am not allowed to share any code anywhere. Sorry about that.

Thank you

Change JavaScript in TypeScript

I would like to translate this code into actual TypeScript. Could you help me there?

import mongoose, { Promise } from 'mongoose';
Promise = global.Promise;

const db = {};

db.mongoose = mongoose;

db.user = require("./user.model");
db.role = require("./role.model");

db.ROLES = ["user", "admin", "moderator"];

export default db;