Why is my dropdown list showing differently on phone than desktop and how can I fix it?

I have a normal select/option setup for a dropdown list and on desktop it looks like normal: https://imgur.com/6xaHjjd.

However, on the phone it instead uses some native phone list, something that looks like this: https://imgur.com/Avftd0N.

This could be all fine, the problem is that in some places I have made my own multi select dropdown list which looks like this: https://imgur.com/2n8SnsL. This list will show like this on both desktop and phone, since it is just made up of divs.

Questions

  1. Can I somehow force all devices to use the same type of dropdown on a normal select/option setup?
  2. Should I?
  3. If not, would you recommend me to create my own dropdown lists too so that I get the same behaviour for both normal and multiple select dropdown lists? It is sort of ugle when one dropdown shows as e.g. native android and one as a “normal” dropdown on the phone.

How to set error state for MUI Textfield without creating a state variable

I currently have 10+ input fields that require form validation against empty user input. It seems the conventional route is to create a state variable to handle this:

const [error, triggerError] = React.useState(false)

and trigger it onSubmit if the value is empty

userInput === '' ? triggerError(true) : triggerError(false)

Issue

However, as the number of form elements scale, so too do these state variables, which is undesirable as it clutters the code. Is there a way to forcibly set the textfield to an error state from the onSubmit function or from the component itself?

Attempted Solutions

(1) From onSubmit: document.getElementById(e.target.id).error = true

(2) From the TextField component: error: {this.value === '' ? true : false}

Possible Solution?

For MUIv4, this is the inspect element output of getElementById(e.target.id):

MuiInputBase-root MuiOutlinedInput-root Mui-error Mui-error MuiInputBase-fullWidth MuiInputBase-formControl MuiInputBase-multiline MuiOutlinedInput-multiline MuiInputBase-marginDense MuiOutlinedInput-marginDense

Perhaps we can append the error CSS class to trigger the error from the onSubmit function?

Please let me know if I can clarify the question in any way and thanks in advance

javascript const = “filepath” for react project

Full disclosure i have done some Google searching on this but i’m aware i may not be asking the correct questions to find what i’m looking for.

I’m using a react template found on Github for an internal application for work that i intend to utilize for searching a json file.

link for reference – Link

the source file in the example is like this:

const initialDetails = [
  {
    id: 1,
    imgPath: "/assets/img/1.png",
    name: "Jane Doe",
    email: "[email protected]",
    address: "New Delhi, India",
  },
  {
    id: 2,
    imgPath: "/assets/img/2.png",
    name: "Mary Rosamund",
    email: "[email protected]",
    address: "Tbilisi, India",
  },
  {
    id: 3,
    imgPath: "/assets/img/3.png",
    name: "Sherlock Watson",
    email: "[email protected]",
    address: "Baker Street, India",
  },
  {
    id: 4,
    imgPath: "/assets/img/4.png",
    name: "John Holmes",
    email: "[email protected]",
    address: "Baker Street, India",
  },
  {
    id: 5,
    imgPath: "/assets/img/5.png",
    name: "Mycroft Lestrade",
    email: "[email protected]",
    address: "London, India",
  },
];

export default initialDetails;

What i would like to is for the equivalent of const initialDetails = “jsonFilePath”

The file i need to query is updated once a minute.

What is the standard way to perform this type of function?

As i’ve stated, i may not be asking the correct questions needed to obtain this solution through Google so thats what led me here.

how to estimate how much until the download will be finished and then show it on the site as a progression bar+ timer

“pretty much i know that i have to do it in java but i really don t know anything about java, only thing i knew how to do is how to make the page not freeze up during changes of the page, through AJAX

pretty much i wanted to challenge myself by implementing the yt-dlb fork for youtube, it works great but i got stuck at adding a timer that tells the user how much time until the converted file will be ready for downloading (what i mean by this is strictly, the time from when the users press convert until the button for them to download the said file appears.)

I don t plan on deploying this anywhere, i just wanna learn how to do it

i tried looking onto some forums but for no use

only thing i tried is this

<h1>Yeqwfwq</h1>

<div id="message"></div>

<form id="download-form">
    <label for="youtube_url">YouTube video URL:</label>
    <input type="text" name="youtube_url" id="youtube_url">
    <br><br>
    <label for="format">Select a format:</label>
    <select name="format" id="format">
        <option value="mp3">MP3</option>
        <option value="mp4">MP4</option>
    </select>
    <br><br>
    <button type="submit">Convert</button>
</form>

<div id="progress-bar" style="display:none">
    <div id="progress" style="background-color: #4CAF50; width: 0%; height: 20px;"></div>
    <div id="progress-text">Conversion progress: <span id="progress-percent">0%</span></div>
    <br>
</div>

<script>

    $(document).ready(function() {

        // Handle form submission
        $("#download-form").submit(function(event) {
            event.preventDefault();
            var form = $(this);
            var message = $("#message");
            var url = form.find("#youtube_url").val();
            var format = form.find("#format").val();

            // Check if the YouTube URL is valid
            if (url.trim() === "" || !isValidYoutubeUrl(url)) {
                message.html("Please enter a valid YouTube video URL");
                return;
            }

            // Send AJAX request to start download
            $.ajax({
                type: "POST",
                url: "download.php",
                data: {
                    youtube_url: url,
                    format: format
                },
                beforeSend: function() {
                    message.html("Starting download...");
                    $("#progress-bar").show();
                },
                xhr: function() {
                    var xhr = $.ajaxSettings.xhr();
                    if (xhr.upload) {
                        xhr.upload.addEventListener('progress', function(event) {
                            var percent = 0;
                            var position = event.loaded || event.position;
                            var total = event.total || event.totalSize;
                            if (event.lengthComputable) {
                                percent = Math.ceil(position / total * 100);
                            }
                            $("#progress").width(percent + '%');
                            $("#progress-percent").html(percent + '%');
                        }, true);
                    }
                    return xhr;
                },
                success: function(data) {
                    message.html(data);
                    $("#progress-bar").hide();
                },
                error: function() {
                    message.html("An error occurred while downloading the video");
                    $("#progress-bar").hide();
                }
            });
        });

        // Validate YouTube URL
        function isValidYoutubeUrl(url) {
            var pattern = /^(https?://)?(www.)?(youtube.com|youtu.be)//;
            return pattern.test(url);
        }

    });
</script>


but everytime i would try to download something, the timer would show after download is finished.

this would be the php code that does all the job

<?php

// Check if YouTube video URL and format are set
if (isset($_POST['youtube_url']) && isset($_POST['format'])) {

    // Get YouTube video URL and format
    $youtube_url = $_POST['youtube_url'];
    $format = $_POST['format'];

    // Validate YouTube URL
    if (preg_match('/^(https?://)?(www.)?(youtube.com|youtu.be)//', $youtube_url) !== 1) {
        die("Please enter a valid YouTube video URL");
    }

    // Build yt-dlp command
    $cmd = "yt-dlp --yes-playlist -o downloads/%(title)s.%(ext)s " . escapeshellarg($youtube_url);

    // If format is mp3, add the --extract-audio and --audio-format mp3 options
    if ($format === "mp3") {
        $cmd .= " --extract-audio --audio-format mp3";
    }

    // If format is mp4, add the --merge-output-format mp4 option
    if ($format === "mp4") {
        $cmd .= " --merge-output-format mp4";
    }

    // Execute yt-dlp command
    exec($cmd, $output, $return);

    // Check if the download was successful
    if ($return === 0) {
        // Find the downloaded file
        $files = glob('downloads/*.' . $format);
        if (count($files) > 0) {
            $filename = $files[0];
            // Set headers to download the file
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
            header('Content-Length: ' . filesize($filename));
        } else {
            echo "An error occurred: downloaded file not found";
        }
    } else {
        echo "An error occurred while downloading the video";
    }

    // Add download button
    echo '<a href="downloads/' . basename($filename) . '" download>
    <button>Download Converted File</button>
</a>';

} else {
    echo "Please enter a YouTube video URL and select a format";
}

?> 






and this would be the code that handles the HTML page


<!DOCTYPE html>
<link rel="stylesheet" href="style.css">
<html>
<head>
    <title>YouTube Downloader</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

    <h1>YouTube Downloader</h1>

    <div id="message"></div>

    <form id="download-form">
        <label for="youtube_url">YouTube video URL:</label>
        <input type="text" name="youtube_url" id="youtube_url">
        <br><br>
        <label for="format">Select a format:</label>
        <select name="format" id="format">
            <option value="mp3">MP3</option>
            <option value="mp4">MP4</option>
        </select>
        <br><br>
        <button type="submit">Convert</button>
    </form>

    <script>

        $(document).ready(function() {

            // Handle form submission
            $("#download-form").submit(function(event) {
                event.preventDefault();
                var form = $(this);
                var message = $("#message");
                var url = form.find("#youtube_url").val();
                var format = form.find("#format").val();

                // Check if the YouTube URL is valid
                if (url.trim() === "" || !isValidYoutubeUrl(url)) {
                    message.html("Please enter a valid YouTube video URL");
                    return;
                }

                // Send AJAX request to start download
                $.ajax({
                    type: "POST",
                    url: "download.php",
                    data: {
                        youtube_url: url,
                        format: format
                    },
                    beforeSend: function() {
                        message.html("Starting download...");
                    },
                    success: function(data) {
                        message.html(data);
                    },
                    error: function() {
                        message.html("An error occurred while downloading the video");
                    }
                });
            });

            // Validate YouTube URL
            function isValidYoutubeUrl(url) {
                var pattern = /^(https?://)?(www.)?(youtube.com|youtu.be)//;
                return pattern.test(url);
            }

        });
    </script>

</body>
</html>



`

`

Import async vanilla js function into react component [duplicate]

I created a function that retun a city using public Ip address. Inside that function I get result but unable to get result into another react component.

getCity.js

const { publicIpv4 } = require("public-ip");
export async function currentCity() {
  let ip = "";
  let city = "";
  // Get IP
  try {
    ip = await publicIpv4();
  } catch (err) {
    console.log(err);
  }

  // Get City From Ip and save
  fetch(`https://ipapi.co/${ip}/json/`)
    .then(function (response) {
      response.json().then((jsonData) => {
        // console.log(jsonData.city);
        city = jsonData.city;
        // console.log(`city: ${city}`);
      });
    })
    .catch(function (error) {
      console.log(error);
    });

  return city;
}

WeatherCard.js

import React, { useState } from "react";
import { currentCity } from "./getCity";

const WeatherCard = () => {
  const [city, setCity] = useState("");

  setCity(currentCity());
  console.log(city);

  return <div></div>;
};

export default WeatherCard;

Use references/pointers to JS Array declared outside of function

I am writing a small tictactoe game in Angular.

I have a function checkForWin() which checks all the possible winning combinations for a win. (Horizontal, Vertical, and Diagonal)

The function works correctly when I declare/init potentialWinningCombos inside of checkForWin()

checkForWin(){
  for(let combo of potentialWinningCombos){  
    let potentialWinningCombos: string[][] = [
       //Horizontal
       [this.gb[0][0], this.gb[0][1], this.gb[0][2]],
       [this.gb[1][0], this.gb[1][1], this.gb[1][2]],
...

So that’s fine and all, but my original design was to declare/init potentialWinningCombos outside of checkForWin() (in the component — and of course I’d iterate over this.potentialWinningCombos instead of the local variable)

With this approach I always get empty strings (the initial values).

My original thought was that when I declare/init potentialWinningCombos with a reference to this.gb[0][0], then it would simply be a reference, but it seems that is not the case…

Why?
Additionally, is there any possible way to keep my original design (using a reference/pointer) so the object isn’t recreated everytime checkForWin() is called? (I know here it’s no big deal, but imagine another case where this is a massive object…)

Axios put request returns 404 (Not Found) React JS

I am trying to make an update functionality works. If a person name already exist and I filled in the phone number, it will say smthg like,

name already exist, replace the phone number instead?

If the person name does not exist, it will create a new object and store the info in the database. The problem right now is that I keep on getting errors ‘PUT http://localhost:3001/persons/undefined 404 (Not Found)’ . I see that the undefined is related to id . But I already included it in the parameter of the function as well as in update method. How can I fix this ? Here is the code,

  const App = () => {
  const [persons, setPersons] = useState([])

  const [newName, setNewName] = useState('')
  const [newNumber, setNewNumber] = useState('')
  const [searchTerm, setSearchTerm] = useState("")

  const addName = (event, id) => {
    event.preventDefault()

    const nameObject = {
      name: newName,
      number: newNumber
    }

    const isNameExist = (value) => persons.some(person => person.name.includes(value))

    const changeNumberText = 'is already added to phonebook, replace the old number with a new one ?'
    
    if ( isNameExist(nameObject.name) && window.confirm(`${isNameExist(nameObject.name)} ${changeNumberText}`)) {
      personService
        .update(id, nameObject)
        .then(response => {
          setPersons(persons.concat(response.data))
          setNewName('')
          setNewNumber('')
        })
    } else if(!isNameExist(nameObject.name)) {
      personService
        .create(nameObject)
        .then(response => {
          setPersons(persons.concat(response.data))
          setNewName('')
          setNewNumber('')
        })
      }
  }

  ................

persons.js

import axios from 'axios'
const baseUrl = 'http://localhost:3001/persons'

const getAll = () => {
  return axios.get(baseUrl)
}

const create = newObject => {
  return axios.post(baseUrl, newObject)
}

const update = (id, newObject) => {
  return axios.put(`${baseUrl}/${id}`, newObject)
}

const deletePerson = (id) => {
  return axios.delete(`${baseUrl}/${id}`)
}

export default { 
  getAll: getAll, 
  create: create, 
  update: update,
  delete: deletePerson
}

Unable to remove textfield value in Ionic Angular

I’m Working on a project which is made in ionic and angular the issue i’m facing is whenever admin creates as user, user gets a signup link. when user opens a link a signup form shows then i’d applied all validations on it the issue is browser automatically fills the username field with it’s may be cache value but after clicking it’s get validated i want to validate it on page load but value is not present there it’s empty.
i’ve attache screenshots fro the same.

enter image description here

after clicking anywhere on page

enter image description here

this validation works.

Anyone knows what can i do here. I want to show validation on page load if there is a wrong value

How can I make photopea.com offline?

Https://www.photopea.com
I have tried to download this website with httrack. Also used plugin in webstore. But I can’t run it properly in (offline) html viewer. So how can I download it and make it offline?

Already tried Httrack and Save all resources plugin.

Uncaught (in promise) FirebaseError: Missing or insufficient permissions when trying to update collection

i am createing a microblogging app using firebase firestore and im getting this error

`const handleNewPostSubmit = async (e) => {
e.preventDefault();

const createdAt = new Date().toISOString();

await firestore.collection('posts').add({
  text: newPostText,
  createdAt,
});`

this is the code i used but i get the error Uncaught (in promise) FirebaseError: Missing or insufficient permissions.

and im also getting the warning
[2023-02-24T03:48:58.451Z] @firebase/firestore: Firestore (9.17.1): Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficient permissions

i wanted this to create a collections posts and add the new post to it

Line break in react text area being treated as space wrongly and can be removed with trim()

I have a text area like below which I try to remove the leading and trailing spaces of the string but I want to include the number of new line charactor in the string.

const [textValue, setTextValue] = useState('')

const onChangeValue= ({target: {value}}) => {
    console.log(value.length);
    console.log(value.trim().length);
    setTextValue(value);
};

<textarea
     onChange={onChangeValue}
     noAutoResize
     width={'100%'}
     height={'15em'}
     value={textValue}
     maxLength={maxLength}
/>

If I keep pressing the enter button on the textArea to add line breaks, the value.length keep increasing but value.trim().length always remains in 0.

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim, the trim() method removes whitespace only

Why it it also remove my line break? Is there any way to achieve such requirement?

unexpected behaviors on classes when testing with jest

I’m working on some tests on my project, and have run in to some weird behaviors.

My code looks something like this:

export class Variable {
  b;

  constructor() {
    this.b = 'B';
  }

  changeValue = () => {
    this.b = 'changed B';
  };
}

export class DerivedVariable {
  v;

  constructor(v: Variable[]) {
    this.v = v;
  }
}

export class Store {
  a;

  v;

  initialize = () => {
    this.a = new Variable();
  };

  get computedValue() {
    return [this.a];
  }

  get computedInstances() {
    return new DerivedVariable(this.computedValue);
  }
}

and my test code:

test('test', () => {
    const { a, computedValue, computedInstances, initialize } = new Store();

    initialize();

    expect(computedValue[0].b).toBe('B');

    computedValue[0].changeValue();

    expect(a.b).toBe('changed B');

    expect(computedInstances.v[0].b).toBe('changed B');
  });

I figured running the initialize function would populate the class variable, which would allow the test to pass.

However, the results of the test returns something like:

 TypeError: Cannot read properties of undefined (reading 'b')

      24 |     initialize();
      25 |
    > 26 |     expect(computedValue[0].b).toBe('B');

Does jest have an asynchronous behavior when it comes to creating class instances?

Thanks in advance.

  • On a side note, I’ve run into a similar issue when testing with class variables after calling a function that mutates it, I assume the two issues are related.

Load images using webs urls with js

First of all I would like to inform that I’m very very new to JavaScript, I’ve been working on a super simple generator, basically all I want is to load an image from a random website on my html page using a form structure, using just vanilla JavaScript… I thought it was going to be easy but I cant seem to figure it out… This the code I’ve been working on:

document.getElementById(“byForm”).addEventListener(‘submit’, function(event) {

event.preventDefault();

let imageUrl = document.getElementById("imageLink").value;

let img = new Image();

img.src = imageUrl;

img.onload = function() {
    document.getElementById("imageContainer").appendChild(img);
};

})

The code above is the climax of several attempts that I’ve been trying on for the past few hours, created a div below the form application where the images are supposed to load in but nothing is happening. also the “imageLink” is the type=url id that i gave it. Can someone explain to me the correct way of doing this or if I’m missing something? Thanks!

javascript could not find the tr element

I visited a private website, and I want to retrieve the content of a tr element. However, document.querySelector("tr") cannot obtain the content even though I cached the page and confirmed that the tr element exists by opening the text file. Furthermore, even when I opened the cached page in the browser, I still couldn’t get the result. Why is this?