Default select option based on current year

I need a JS that autoselect as default option the current year from this select-dropdown.
Now we are in 2022, so the defaul option must be 2022.

Thanks.

<select id="yearDP">
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2022">2023</option>
<option value="2022">2024</option>
<option value="2022">2025</option>
<option value="2022">2026</option>
</select>

Why only one value of the tittle after clicking dynamic button

I work with Google Books Api and display card with books and creating them dynamic in js with button like this:

$.ajax({
            url: "https://www.googleapis.com/books/v1/volumes?q=subject:fiction",
            dataType: "json",
    
            success: function(data) {
                for (i = 0; i< 20; i++){
                    const content = `
                    <div class="card my-3" style="width: 18rem;">
                    <img class="mx-auto card-img-top book-cover imgs thumbnail" src="${data.items[i].volumeInfo.imageLinks.thumbnail}" style="width:170px; height:230px;" alt="">
                    <div class="card-body" id="results">
                        <h5 class="card-title" style="font-weight:bold">${data.items[i].volumeInfo.title}</h5>
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                        <div class="d-flex">
                        <div class="dropdown " style="margin-right:8px;">
                            <button class="btn btn-dark dropdown-toggle" 'type="button" style="height:2.5rem;" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            Add
                            </button>
                            <div class="dropdown-menu" aria-labelledby="dropdownMenu2">
                            <button class="dropdown-item iWantToRead" id = "iWantToRead" value='${data.items[i].volumeInfo.title}' type="button">I want to read</button>
                            <button class="dropdown-item" type="button">Read</button>
                            <button class="dropdown-item" type="button">I want to buy</button>
                            </div>
                        </div>                        
                        <button type="button" name="add_review" id="add_review" class="btn btn-dark">Review</button>
                        <a href="${data.items[i].accessInfo.webReaderLink}" class="btn mx-auto btn-dark" style="height:2.5rem;">Read</a>
                        </div>
                    </div> `;
                    card.innerHTML += content;

and I went to attach tittle of the book to button and depending what btn user click the tittle will display. But I am having problem that I am only getting tittle of first book no matter what btn I click

$('.iWantToRead').unbind().click(function(){
                        var button = document.getElementById('iWantToRead');
                        var tittle = button.getAttribute('value');
                        var thumbnail = button.getAttribute('data-value');
                        $.ajax({
                            type: "POST",
                            url: "bookshelf.php",
                            data: 
                            {
                                action:'iWantToRead',
                                tittle: tittle,
                                thumbnail: thumbnail
                            },
                            success: function(html){    
                                console.log(html);
                                
                            }
                        })
                    });

How to access a variable from outside of Ajax code [duplicate]

I would like to make fileContent variable available outside of $.ajax code.

var fileContent = "";

$.ajax({
method: "POST",
url: "php/somefile.php",
data: {"nazwaProduktu": "nazwa produktu"},
}).done(function( data ) {
        var result = $.parseJSON(data);
        if (result!== null){
            var len = result.length;
                for(var i=0; i<len; i++){
                    fileContent=fileContent+result[i].nazwa+";";
                    fileContent=fileContent+(result[i].komentarz)+"n";
                }
            }
        }
);

console.log(fileContent); //here I see fileContent empty! I need to have it updated by the above code.

Can you please advice how can I do this?

How can i store a selected in sessionStorage javascript?

im trying to store the <iput type='radio'/> that the user choose in sessionStorage…

in sessionStorage it should look like this:
key: user option.
value: option that user choose

i tried like this:

  const store = document.getElementById('rb');
  sessionStorage.setItem('user-selected-option', store.value);

but didn’t work

im pretty stuck right now, can you guys help me with this?

heres my code:

html:

<section>
        <label id="rb">select your option</label>
        <label id="rb">
          <input type="radio" name="options" value="1" />one</label>
        <label id="rb">
          <input type="radio" name="options" value="2" />two</label>
        <label id="rbb">
          <input type="radio" name="options" value="3" />three</label>
      </section>

js:

function mSessionStorage() {

}

const btn = document.getElementById('submit-btn');

function submit() {
  mSessionStorage();

}

btn.addEventListener('click', submit);

Do I follow solid principles by writing this code.? [closed]

Is this code break SOLID principles and bad practice because it has side effect? ?

var app = exports = module.exports = {};
app.prototype = Object.create(expressApp.prototype);

app.config = function config() {
    this.set("trust proxy", true);
    this.use(someMiddleware)
    this.use(json());
}

And I will use it like that

const {app} = require('file')

app.config()

Instead of copying and pasting same code over and over

How do i send a response to the front end whether or not the if statement is true

How do i send a response to the front end whether or not the if statement is true
i tried to use res.status() but when i look at the response it has not changed
im recieving this response from the front end
Request URL: http://localhost:3000/register?
Request Method: GET
Status Code: 304 OK
even though im trying to get a response from the backend with either res.status(200)
or res.status(400)

const UserModel = require("./Server/models/User")
const Post = require("./Server/models/Post")
const mongoose = require("mongoose")
const bodyParser = require("body-parser")
const express = require("express")
const app = express()

mongoose.connect("mongodb://localhost:27017/BlogSite")




    



app.use(express.json())

app.get("/",(req,res)=> {
    res.send("Home")
})




app.post("/api/register",(req,res)=> {
  
    console.log(req.body)
    const username =(req.body.username)
    const password = (req.body.password)
 
    UserModel.create({username:username,password:password},(err) => {
        if (err) {
            console.log(err)
        }
        else{
            console.log("User Created")
            res.status(200).send("Home");
        }
    })
    

    
    
    
});

app.post("/api/login",(req,res)=> {
UserModel.find({username: req.body.username,password :req.body.password},(err,data) =>{
    

    if (data.length == 1){
        console.log("Logged in")
       app.post("/api/restatus",(req,res)=>{
           console.log("sent")
       })
    }
    else{
        console.log("Wrong Email or password")
        res.status(401)
    }
})
})



app.listen(3001,()=> {
    console.log("listening on port 3001")
})

Frontend

import React, { useState } from 'react';
import './App.css';

function Register() {
const [username,setUsername] = useState("")
const [password,setPassword] = useState("")


function handleSubmit(event) {
event.preventDefault
fetch("http://localhost:3001/api/register",{
  method:"post",
  headers:{
    "Content-Type" : "application/json"
  },
  body:JSON.stringify({username:username,password:password})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })


} 



  return (
    <div className="App">
      <form onSubmit={handleSubmit}>

        <input placeholder="username" value={username} onChange={ e => setUsername(e.target.value)} />
        <input placeholder="password " value={password} onChange={ e => setPassword(e.target.value)}/>
        <button  type='submit' >Submit</button>
      </form>
    </div>
  );
}

export default Register;

Viewport error when embedding PDF in HTML

I’m using the answer by batfan to this seemingly famous SO question: Recommended way to embed PDF in HTML?

I inserted the following into my HTML:

<embed src="/pdf/3" height="1600" width="1600" type="application/pdf">

This does not work as intended: The PDF title shows correctly and the viewer loads but no PDF is shown. When I inspect the blank PDF viewer I see the following error:

Uncaught TypeError: Cannot read property 'x' of undefined
    at Viewport.getPageInsetDimensions (viewport.js:1161)
    at Viewport.getPageScreenRect (viewport.js:1185)
    at PDFViewer.viewportChanged_ (pdf_viewer.js:1044)
    at Viewport.viewportChangedCallback_ (pdf_viewer.js:254)
    at Viewport.updateViewport_ (viewport.js:398)
    at Viewport.resize_ (viewport.js:425)
    at viewport.js:1149
    at Viewport.mightZoom_ (viewport.js:509)
    at Viewport.setDocumentDimensions (viewport.js:1138)
    at PDFViewer.setDocumentDimensions_ (pdf_viewer.js:1264)

Tested in Chrome and Firefox. Any idea?

console.log shows object promise, a friend of mine said that it’s because the API is in JSON but I don’t understand where I went wrong

async function vreme(){
  let stanje = await fetch("api.openweathermap.org/data/2.5/weather?lat=42.82865&lon=20.46023&appid=ad163d4c65378315beb9a137e07daf73&units=metric")

  let prognoza = await stanje.json()
  return prognoza
}

console.log(vreme())

console.log shows object promise. A friend of mine said that it’s because the API is in JSON but I don’t understand where I went wrong.

Next JS data handeling

_APP.JS

function MyApp({ Component, pageProps }) {
  let primary = 'darkMode_Primary';
  let secondary = 'darkMode_Secondary'
  return (
    <Layout primary_super={primary} secondary_super={secondary}>
      <Component {...pageProps} />
    </Layout>
  )
}

export default MyApp

LAYOUT.JS

export default function Layout({ children , primary_super, secondary_super}) {

  return (
    <>
      <Navbar  primary={primary_super} secondary={secondary_super}/>
      <main>{children}</main>
      <ModeSwitch primary={primary_super} secondary={secondary_super}/>
    </>
  )
}

NAVBAR.JS

export default function Navbar(props) {

    const click = ()=>{
        console.log('USS')
    }

    const Primary = theme[props.primary]
    const Secondary = theme[props.secondary]
    return (
    <div className="NAV" id="NAV" style={Primary}>
        <div className="NAV_BOX_FULL NAV_LEX" style={Secondary}> 
            <img src="/NAV_img/cat.png" alt="" className="NAV_logo1 NAV_logo"/>
            <h3 className="NAV_head"  onClick={click} >SilenxIka</h3>
        </div>
    </div>
  )
}

what i want to do is, when someone triggers that onClick fuction in navbar.js, the primary and secondary in _app.js

File style:
Navbar.js is inside of Layout.js and Layout.js is used in _app.js

Iterate an Object and Append as FormData (Including files, and normal text)

I’m trying to upload files using formData, but also I do have some other fields that I need to include in the formData, so because I have an long object I want a automatic loop that iterates through the object I have and fills the form data.

For example this is my object:

const data {
  name: 'Adrian',
  files: [many other file uploads],
  houses: ['Mansion Q', 'Small Tini Sini House :P']
}

And this is the data I need to stimulate:

const formData = new FormData();
// someway to formData.append('the key', 'value of the key')

What does myFunction(this) pass into the this parameter?

In my HTML I have <span><input type="text" class="tester" onfocusout="tester(this)" /></span>
When I console.log the passed in value for ‘this’ I get: enter image description here

Now from within my Javascript I want to grab an element in just the way the ‘this’ paramater did. .innerHTML logs a string and .getElementsByClassName an array. If I define the index of that array it will return input.tester.
How can I get the ‘live’ HTML element like in the picture? Thank you.

How to loop canban cards accordnig their status

Hello guys im begginer and i need help.I want cards to be in place according their status, not in all statuses same card like this.enter image description here

Iam using laravel inertia and vue js.
This is my laravel controller:

    public function index()
{

    $leads = Lead::has('status')->get();

    return Inertia::render('Leads/LeadBoard',[

        'leads' => $leads,

        'statuses' => function () {
            return LeadStatus::orderBy('id')->get()
                ->transform(function ($status) {
                    return [
                        'id' => $status->id,
                        'status_name' =>  $status->status_name
                    ];
                });
        },

    ]);

}

and mu vue file:

<script>
import AppLayout from "@/Layouts/AppLayout";


export default {
    name: "LeadBoard",
    components: {
        AppLayout,
    },
    props: {
        statuses: Array,
        leads: Array,

    },
}

My loop for cards which is wrong:

v-for="lead in leads"
:key="lead.id"

and my loop for status columns which works fine:

v-for="status in statuses"
                        :key="status.id"

Typescript error: This expression is not callable. Type ‘never’ has no call signatures

I am getting a TypeScript error on onToggle(eventKey === activeEventKey ? null : eventKey) – This expression is not callable. Type ‘never’ has no call signatures. I am not sure how to resolve this.

import React from 'react'
import useAccordionContext from '../../../hooks/useAccordionContext'

interface Props {
  eventKey: string | undefined
  id: string | undefined
  className: string
  onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void
}

const useAccordionClick = (
  eventKey: string | undefined,
  onClick: {
    (event: React.MouseEvent<HTMLButtonElement, MouseEvent>): void
    (arg0: React.MouseEvent<HTMLButtonElement, MouseEvent>): void
  }
) => {
  const { onToggle, activeEventKey } = useAccordionContext()
  return (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    onToggle(eventKey === activeEventKey ? null : eventKey)

    if (onClick) {
      onClick(event)
    }
  }
}

const Toggle: React.FC<Props> = ({
  eventKey,
  onClick,
  children,
  ...otherProps
}) => {
  const accordionClick = useAccordionClick(eventKey, onClick)
  return (
    <button
      onClick={accordionClick}
      {...otherProps}
    >
      {children}
    </button>
  )
}

export default Toggle

How to dynamically load ESM from CDN or node_modules depending on browser/Node context?

I’m writing an ES6 module that will work either client or server side. For example, it uses mermaid-js, which is both available via CDN URL and installable into Node. To keep the library as small as possible, I’d rather not bundle it with my module. I’d like it to dynamically do the following

  • when it is running in a browser, it loads it mermaid.js from CDN
  • when it is running in Node, it loads it locally, from node_modules.

I do know how to use dynamic imports, and I’m sure I can figure out the code to make it work, but I figured this is one of the hallmark reasons for ESM and there should some standard way to do it, but I found none. I looked far and wide, and all I found was Load file local or from cdn, but that loads the module into a web page, not directly into Javascript or Typescript.