Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)

whenever i try to use a ‘onclick’, it gives me reading ‘null’ error. But i used almost the same line of code previously and it worked.
heres the code:

const logoutBtn = document.querySelector('#logout-b')
logoutBtn.onclick = function(){
    empty();
    if(fields.email && fields.password === null){
        console.log("successfully Logged out");
    }
}
//output:Uncaught TypeError: Cannot set properties of null (setting 'onclick')

the empty(); function clears the fields.
Here is the other code that worked correctly

const loginBtn = document.querySelector('.login-button');
loginBtn.onclick = function(){
    refresh();
    fields = {
        "email": email,
        "password": password
    }
    if(fields.email && fields.password !== null || undefined){
        window.location.href = "home.html";
    }else{
        console.log("null")
    }
}
//this line successfully sets the object's fields to the email, password and sets the window location to 'home.html'

does anyone know what the issue is?

Show Div/Hide if one of the select options from optgroup is selected Javascript

I’m trying to modify and example from this same page but its not working as I want.

I have two groups in a select, and I want chose any option from one of the second optgroup “Unique” and if you select any option from that group, show a Div. Else don’t show nothing.

<div class="form-floating mb-3 mt-3">
<table>
  <tr>
   <td><input class="form-control input-lg email" type="email" name="mail[]" required /> 
</td>
  <td>
    <select class="form-select" name="skills[]" required>
      <optgroup Class="unique" label="Common">
        <option value="Extraction">Extraction</option>
        <option value="Hunting">Hunting</option>
        <option value="Farming">Farming</option>
      </optgroup>
      <optgroup class="unique" label="Unique">
        <option value="Diplomacy">Diplomacy</option>
        <option value="Survival">Survival</option>
      </optgroup>
    </select>
  </td>
<td>
  </tr>
</table>  
</div>  

<div class="mt-5 extras" id="mydiv">
<h4 class="text-dark">Check</h4>
Increased through making items, sewing and cooking.<br>
<input class="form-check-input" type="checkbox" name="checkpoint" checked required/>  
</div>

Selecting a random amount of checkboxes JS jQuery

    $('#select_all').on('click', function () {
        if (this.checked) {
            $('.check').each(function () {
                this.checked = true;
            });
        } else {
            $('.check').each(function () {
                this.checked = false;
            });
        }
    });
    $('.check').on('click', function () {

        if ($('.check:checked').length == $('.check').length) {
            $('#select_all').prop('checked', true);
        } else {
            $('#select_all').prop('checked', false);
        }
    });

Need to alter this above Select All code to only select some random amount of check boxes, like below code example. Any help for this?

$(".random-pick").click(function() {
  var maxAllowed = 6;
  // Count checkboxes
  var random_checkboxes = $("#content_subscribtion_ input.checkbox").size();
  // Check random checkboxes until "maxAllowed" limit reached
  while ($("#content_subscribtion_ input.checkbox:checked").size() < maxAllowed) {
    // Pick random checkbox
    var random_checkbox = Math.floor(Math.random() * random_checkboxes) + 1;
    // Check it
    $("#content_subscribtion_ input.checkbox:nth-child(" + random_checkbox + ")").prop("checked", true);
  }

  return false;
});

Socket connects only when react app is terminated

I’m trying to set up socket on my already existing react.js application. It’s a basic one that uses express and node to connect to a mongoose DB. I’ve set up socket on the client side.

Main.js

import { io } from 'socket.io-client'
var socket = io.connect('http://localhost:3000')
function Home(props) {
      const {username} = useParams()
      const [Username , setUsername] = useState("")
      const [SearchedData, setSearchedData] = useState() 
      const [Data, setData] = useState()
          return (
          <div className="App">
            <NavBar CurrentUser={username} Search={setSearchedData}/>
        {(Data !== undefined)? <Content CurrentUser={username} Data={SearchedData} HomeData={Data}></Content>
          :
        <Loading></Loading>}
        </div>)
    }

server.js

require('dotenv').config('./secret.env')
const express = require("express")
const app = express()
const cors = require("cors")
const router = express.Router();
const mongoose = require("mongoose")
const mongo = require("mongodb")

const server = app.listen(3000, () => {
    console.log("listening to on 3000")
})
var socket = require('socket.io')

var io = socket(server)

io.on("connection",(socket) => {
    console.log("Socket Connection")
})

 app.use('/user', require("./route/NodeRoute"))
 app.use('/', require('./route/LoginRoute'))
 app.use('/create',require('./route/Create'));

I use run npm start and nodemon serve.js to run the frontend and backend.
But the connection to the socket is made only when I terminate the connection to my react app (CTRL + C) in the terminal. The app run on port 3000 and server runs on 3001

I’ve tried using another port but it didn’t work.

Javascript: Preventing a generator from repeating options until all options are exhausted?

I feel I should preface this by saying I am just now really learning how to incorporate anything into Javascript, so please explain things and answers at a rudimentary level.

I am trying to figure out how to make this script NOT REPEAT an option until ALL options have been exhausted at least once. This is a common problem with Math.random from what I see, but I have no idea how to incorporate a fix to make it not repeat.

Any help would be appreciated!

var stratnames_t = {
    '0': "Strategy 1 Name Here",
    '1': "Strategy 2 Name Here",
};
var objectives_t = {
    '0': "Objective 1 Description Here",
    '1': "Objective 2 Description Here",
};

function randomRoulette() {

  document.getElementById("roulette").style.display = "";

  var rand = Math.floor(2 * Math.random());
  document.getElementsByTagName("objective")[0].innerHTML = objectives_t[rand];
  document.getElementsByTagName("stratname")[0].innerHTML = stratnames_t[rand];

};

function main() {
  roulette.addEventListener("click", function() {
    randomRoulette();
  });
}

main();```

How can I make this map filter shorter & better

I think this is not an ideal way of doing filters. I have to type more if else’s and it doesn’t look good.

I found a package called “useFilter”. but can I just make it without using any packages? like with hooks or something.

 
import { AddPosition } from "./../../data/careers/AddPosition";

const Positions = () => {
  const [positions] = useState(AddPosition);
  const [searchTerm, setSearchTerm] = useState("");

   <input
                type="search"
                placeholder="Search"
                onChange={(e) => setSearchTerm(e.target.value)}
              />
             
                   {positions
            .filter((position) => {
              if (searchTerm === "") {
                return position;
              } else if (
                position.category
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.type.toLowerCase().includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.location
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              } else if (
                position.position
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase())
              ) {
                return position;
              }
            })
            .map((position) => (
              <>
                <SinglePosition
                  id={position.id}
                  category={position.category}
                  type={position.type}
                  position={position.position}
                />
              </>
            ))}
        </div>
      </div>
    </div>

How to create a grid layout with variable height elements, but close the spaces?

I’ve tried CSS Grid, Flexbox, and good old display: inline-block; but I can’t seem to get the layout I want.

I’m trying to get a layout that ends up like this…

enter image description here
enter image description here
enter image description here
enter image description here

The little red arrows indicate which way the div should grow if there’s more content. So basically a top section with bottom vertical alignment, and a bottom section with top vertical alignment, and a variable number of columns depending on the browser width.

All I seem to be able to create is this on the bottom…

enter image description here
enter image description here

The bottom is arranged by row, which doesn’t work, and the flex box creates the divs with equal height regardless of content, which is also bad.

I can add html to denote columns for the bottom section, but I can only do that for a specific number of columns, and with all the different devices out there, I’d like to make that responsive.

remove the existing piece form the sqaure and a new one (chess)

I am making a chess game, and I need your help to solve the following problem.

event.target.removeChild(event.target.firstChild);
dragged.parentNode.removeChild(dragged);
event.target.appendChild(dragged);

//dragged is ref to the dragged piece
//event is the drop event

when I move a piece :

  1. I remove the existing piece from the square
  2. I add the new Piece
  3. If the square is empty I just add the piece

note: event.target is a square and the pieces are images.

The problem is when I remove The existing piece from the square, I get the following error:
Failed to execute ‘removeChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

Error opening original Word document from add-in

I am trying to open an existing document (the original file) from within a Word add-in. I do not access to the original file locally, only a url. I have tried:

    var newDoc = context.application.createDocument(base64Image)
    newDoc.open()
    context.sync()

If the base64Image is a .docx file type, it will open a new document as an image (not editable), otherwise I’m getting an error: Uncaught (in promise) RichApi.Error: GeneralException.
When I don’t pass in an argument into createDocument(), it successfully opens a blank document.

I’ve placed the base64Image into the current document using insertFileFromBase64 and insertInlinePictureFromBase64, so I know the base64Image file is supported.

Any other ideas how to open an editable document?

unable return data from promise to other component in react

I have an api posting data on server and i want to get that response in other file.
this is a function in action.js file. I want to return response of this promise to other component where it is called.

export const saveOrder = data => dispatch => {
  fetch(`${baseUrl}/save-order`, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
    body: data,
  })
    .then(res => res.json())
    .then(json => {
      console.log('json1', json);
     **want to return this json variable**
      alert('order placed');
    })
    .catch(error => {
      console.log('error in saving', error);
    });
};

this is my component where i want to get its response when order is successfully placed. I have tried async and await but it did not worked.

  const postOrder = () => {
    var data = new FormData();
    data.append('userId', state.user.id);
    dispatch(saveOrder(data));
  };

Why is my exported function call returning undefined in ReactJS?

I’m creating this webapp that will eventually pull live JSON objects from a website, filter them based on some values like name or ID, then push them to a list for rendering. While I have a decent Java background, I’m still very new to React, and rusty in terms of JS and HTML/CSS. I’ve been following tutorials and looking at related questions on this site in order to set this up; so I apologize if there are any rookie errors!

I’ve created this Filter class here:

class Filter {

id;
filterName;
isChecked;

constructor(id, filterName, isChecked) {
    this.id = id;
    this.filterName = filterName;
    this.isChecked = isChecked;
}

setupFilters() {
    var filters = []
    filters.push(new Filter("ACT_CLEAN", "Cleaning", false));
    filters.push(new Filter("ACT_WOODCUT", "Chop Wood", false));
    filters.push(new Filter("ACT_RUN", "Running", false));
    filters.push(new Filter("ACT_EAT", "Eat a Meal", false));
    filters.push(new Filter("ACT_IDLE", "Idle", false));

    return filters;
}

getFilterID() {
    return this.id;
}

getFilterName() {
    return this.filterName;
}

setChecked(bool) {
    this.isChecked = bool;
}

getChecked() {
    return this.isChecked;
}

getCheckedFilters() {
    var checkedFilters = []
    for (var i = 0; i < this.filters.length; i++) {
        if (this.filters[i].getChecked() == true) {
            checkedFilters.push(this.filters[i]);
        }
    }
    return checkedFilters;
}

}

export default Filter
export function getCheckedFilters(){}
export function setChecked(){}
export function getChecked(){}
export function getFilterId(){}
export function getFilterName(){}
export function setupFilters(){}

Which handles all information about a filter, including setting up the initial list of filters with setupFilters(), which is the subject of my question.

After exporting the setupFilters() function, I went over to my TaskList component and added the logic for rendering the list given active filters, as well as set a filter to true for some testing.

TaskList component:

class TaskList extends Component {

state = {
    tasks: [],
    loading: false
}

componentDidMount() {
    this.setState({
        loading: true
    })
    var activeFilters = setupFilters();
    activeFilters[0].setChecked(true);
    console.log("Filters: " + activeFilters);
    axios.get(taskUrl)
        .then((res) => {
            for (var i = 0; i < activeFilters.length; i++) {
                if (activeFilters[i].id == res.data && activeFilters[i].getChecked == true) {
                    this.setState({
                        tasks: res.data,
                        loading: false
                    })
                }
            }
        })
        .catch((err) => {
            console.log(err)
        })
}



render() {
    const { tasks } = this.state
    if (tasks.length === 0) {
        return <p>No Tasks to Show.</p>
    }

    return (
        <ListGroup>
            {tasks.map(t => <TaskItem key={t.id} task={t} />)}
        </ListGroup>
    )
}
}

export default TaskList

However, and this is where my issue comes in… this function returns nothing, undefined. I check it within the scope of this component and it went from a function that would return filter[] to an alias function that was void. Did I export the function incorrectly in the Filter class? Should I call the function differently in a component versus another class or something else? I would appreciate any and all feedback on why this rather simple function doesn’t return anything.

Firebase Functions Finished with status: error

Note: Please read the whole question before marking it as a duplicate, thinking it is the same as this question.

I am writing my first Firebase Function that is supposed to make a collection with a document inside (in Firestore) when a new user registers. The only logs I am getting are the following:

Function execution started

and

Function execution took 194 ms. Finished with status: error.

The versions of the dependencies:

"firebase-admin": "^10.0.2",
"firebase-functions": "^3.20.0"

This is my code:

const functions = require("firebase-functions");

const admin = require("firebase-admin");
admin.initializeApp();

const db = admin.firestore();

exports.newUser = functions.auth.user().onCreate((user) => {
    return db
        .collection("users")
        .doc(user.uid)
        .create(JSON.parse(JSON.stringify(user)));
});

When I tried outputting the user.uid in the logs with

return functions.logger.log(user.uid);

I got the expected results as it output the uid as requested, meaning that the problem isn’t with getting the user.

Any ideas?