Toggle-button failing to provide drop down menu

Good Afternoon,

This is my first project and im attempting to make my nav bar responsive. when re adjusting the size I am having issues with the toggle button working as expected. I expect it to provide a list of drop downs when click on it however nothing happens when I click on the button.

please see code snippets below and thanks in advance : )


  <nav class="navbar">
    <div class="itpslogo"><img src="img/ITPS.png" alt=""></div>
    <a href="#" class="toggle-button">
      <span class="bar"></span>
      <span class="bar"></span>
      <span class="bar"></span>
    </a>
    <div class="navbar-links">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </div>
  </nav>
* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;

}



.navbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #00BFFF;


}

.itpslogo {
    width: 100%;
    height: auto;
    margin: 0.5rem;
}

.navbar-links ul {
    margin: 0;
    padding: 0%;
    display: flex;
}


.navbar-links li {

    list-style: none;

}

.navbar-links li a {
    text-decoration: none;
    color: white;
    padding: 3rem;
    display: block;
    font-size: large;
}

.toggle-button {
    position: absolute;
    top: 0.75rem;
    right: 1rem;
    display: none;
    flex-direction: column;
    justify-content: space-between;
    width: 30px;
    height: 21px;

}

.toggle-button .bar {
    height: 3px;
    width: 100%;
    background-color: white;
    border-radius: 3px;
}

@media (max-width: 800px) {
    .navbar {
        flex-direction: column;
        align-items: flex-start;
    }

    .toggle-button {
        display: flex;
    }

    .navbar-links {
        display: none;
        width: 100%;
    }

    .navbar-links ul {
        width: 100%;
        flex-direction: column;
    }

    .navbar-links ul li {
        text-align: center;
    }

    .navbar-links ul li a {
        padding: .5rem 1rem;
    }

    .navbar-links.active {
        display: flex;
    }
}
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]

toggleButton.addEventListener('click', () => {
    navbarLinks.classList.toggle('active')
})

How to add Current Date und Time into Table?

how can i add the current date and time with this format: 2022-07-17 17:50:20 ?

i allready managed it with a input value but i need the current time.

Can someone help me please?

function button1( table ){
        
var tableRef = document.getElementById(table);
var newRow   = tableRef.insertRow(-1);
        
var newCell  = newRow.insertCell(0);
var newElem = document.createElement( 'input' );
newElem.setAttribute("name", "timestamp");
newElem.setAttribute("type", "text");
newElem.setAttribute("value", " 2022-07-17 17:30:24 ");
newCell.appendChild(newElem);
        
newCell = newRow.insertCell(1);
newElem = document.createElement( 'input' );
newElem.setAttribute("name", "button_name" );
newElem.setAttribute("type", "text");
newElem.setAttribute("value", "Button_Name");
newCell.appendChild(newElem);

newCell = newRow.insertCell(2);
newElem = document.createElement( 'input' );
newElem.setAttribute("type", "button");
newElem.setAttribute("value", "Delete Row");
newElem.setAttribute("onclick", 'deleteRow(this)')
newCell.appendChild(newElem);

Make mouse draggable image draggable on touch screen

I need your help please!
I have a button that creates a draggable image with the mouse, but I don’t know how to make it draggable on a touch screen.

on this code you can click on the image then move it but not from a mobile or other touch screen

sorry for my english i’am french…

here is the code:

function addimageBouchon() {
  var img = document.createElement("img");
  img.src = "https://votrenourrice.fr/img/bouchon.svg";
  img.height = 50;
  img.width = 50;

  var class_name = "buttonImg";
  img.setAttribute("class", class_name);
  
  document.getElementById("myDiagramDiv").appendChild(img);
   $(img).draggable();
}
.box{
    background: linear-gradient(60deg,  #080808, #606060);
    border: 2mm ridge #696969;
    opacity: 99%;
    padding: 15px;
    overflow-y: auto;
    width: 20vw;
    animation: animate 4s linear infinite;
    
}





.box div h2{
    text-align: center;
    color: orange;
    text-decoration: underline;
    
}
.box div p{
    text-align: center;
    color:palegoldenrod;
    text-decoration: underline;
    font-size: 0.8em;
}

.partieButton{
    display: flex;
    flex-wrap: wrap;
    justify-content:center;
    
    
}
.buttonCreate{
    margin: 3px;
    box-shadow: 3px 3px ;
    border-radius: 6px;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>


<div class="container">
  
        <div class="description">
            <div id="myDiagramDiv" draggable="true" style="width: 70vw; height:100vh; background-color: #DAE4E4;opacity: 80%;"></div>
        </div>
    </div>


<div class="box">
  <div class="partieButton">
          <div class="buttonCreate" >
            <button type="button" class="buttonImg" onclick="addimageBouchon();"><img src="https://votrenourrice.fr/img/bouchon.svg" height ="40" width="40" alt="bouchon" /></button>
          </div>
        </div>
</div>

Mouseover/Mouseout flickering problem on div creation in Slider revolution

I’m not an expert and I would like to make this effect (link1: https://jsfiddle.net/agbuLop1/
link2:https://bryson.qodeinteractive.com/portfolio-carousel/
) on my website on a carousel mad with slider revolution.
Now thanks to a friend who did a script, I have this result (http://www.creativethaipuan.com
). But unfortunately, it’s not working properly, the cursor makes the script exit and enters the function every time I move the mouse and the box is flickering. Here you can see the script I’m using (https://jsfiddle.net/matbonbon/eco2pf8y/9/)

Html:

<html>
    <head>
    <body>
        <!-- split the screen in two divs -->
        <div id="left" class="mydivs">
            <h1>Left</h1>
            <p>This is the left side of the screen</p>
        </div>
        <div id="right" class="mydivs">
            <h1>Right</h1>
            <p>This is the right side of the screen</p>
        </div>
      
      
     </body>
     </head>
     </html>

Script:

var myTexts = {
    "left": "This is the left side of the screen",
    "right": "This is the right side of the screen"
};

function setHoverDiv(e) {
    hoverDiv.innerHTML = myTexts[this.id];
    hoverDiv.hidden = false;
}

function hideHoverDiv(e) {
    hoverDiv.hidden = true;
}

function moveHoverDiv(e) {
    // show the hoverDiv close to the mouse position
    hoverDiv.style.top = e.clientY + "px";
    hoverDiv.style.left = e.clientX + "px";
}

function createHoverDiv() {
    var myDiv = document.createElement("div");
    myDiv.id = "newdiv";
    myDiv.style.position = "absolute";
    myDiv.style.backgroundColor = "red";
    myDiv.style.color = "black";
    myDiv.style.fontSize = "20px";
    myDiv.style.padding = "10px";
    myDiv.style.borderRadius = "5px";
    myDiv.style.zIndex = "1000";
    myDiv.innerHTML = myTexts[this.id];
    // show the myDiv close to the mouse position
    myDiv.hidden = true;
    document.body.appendChild(myDiv);
    return myDiv;
}

var hoverDiv = createHoverDiv();
document.body.addEventListener("mousemove", moveHoverDiv);

var mydivs = document.getElementsByClassName("mydivs");
// use an interator to iterate over the divs
for (var i = 0; i < mydivs.length; i++) {
    // when the mouse hovers the div, create a new div with a text close to the mouse position
    var mydiv = mydivs[i];
    mydiv.addEventListener("mouseover", setHoverDiv);
    // when mouse leaves the div, remove the new div
    mydiv.addEventListener("mouseout", hideHoverDiv);
}

Considering that I’m using it inside the slider revolution module where I can set custom scripts and CSS and I can set a custom Class and Id for any single slide in the carousel.
Hope you can help me to find a solution. Thanks for your time and help.

TypeScript: How to create union type from array property on mapped type?

I am trying to create a union type from the elements of an array in an object that has been annotated to a mapped type. Is it possible to achieve somehow without removing the type annotation?

Example code:

type Persons<Name extends string> = {
    readonly [N in Name]: {
        readonly age: number;
        readonly friends: ReadonlyArray<Name>;
    };
}

type Friends<Name extends string, P extends Persons<Name>, N extends Name> = P[N]["friends"][number]

type Names = 'Bill' | 'Jim' | 'Tom'

// Example with type annotation that I would like to keep
const persons1: Persons<Names> = {
    Bill: {
        age: 40,
        friends: ['Jim']
    },
    Jim: {
        age: 42,
        friends: ['Tom']
    },
    Tom: {
        age: 45,
        friends: []
    }
}

// Example without type annotation (for which it works as expected)
const persons2 = {
    Bill: {
        age: 40,
        friends: ['Jim']
    },
    Jim: {
        age: 42,
        friends: ['Tom']
    },
    Tom: {
        age: 45,
        friends: []
    }
} as const

type Friends1 = Friends<Names, typeof persons1, 'Jim'>
// 'Jim' | 'Bill' | 'Tom' - would like it to be 'Tom'

type Friends2 = Friends<Names, typeof persons2, 'Jim'>
// 'Tom' - as wanted

My guess was that it could be done by deep cloning persons1 but haven’t been able to get the correct type of the clone.

How to create graphic from numerical argument JS (complete newbie)

(added specifics this time)

I am messing around with js at the moment and am now working on a project that takes an argument (4.5) and generates a graphic for a number of filled squares in a bar corresponding to the rating out of 5. Thus far, I have been stumped as to how to achieve this and would appreciate any help anyone is willing to offer
This is the look of the rating system im trying to acheive

I am hoping to acheive this by filling these divs with a color corresponding to the number.

<div style="border-radius: 0px;"></div>
        <div style="
        border-radius: 0px;
    "></div>
        <div style="
        border-radius: 0px;
    "></div>

I want to delete the same part from the two -dimensional array

I would like to compare the two arrangements of the following script to delete the duplicate arrangement.
I used the Filter and Includes function or for statement but failed.
What should I do?

let ground = [
  [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
  [1,3,3,7,7,7,7,8,8,4,4,4,2,2,3,7,1],
  [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
]

let deleteBlock = [[1,3,3,7,7,7,7,8,8,4,4,4,2,2,3,7,1]]

Twitter api returns unsupported authentication; “detail”: “Authenticating with Unknown is forbidden for this endpoint.”

I am trying to send a GET request to https://api.twitter.com/2/users api to obtain some user info, but the response is always

{
  statusCode: 403,
  data: '{n' +
    '  "title": "Unsupported Authentication",n' +
    '  "detail": "Authenticating with Unknown is forbidden for this endpoint.  Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 Application-Only, OAuth 2.0 User Context].",n' +
    '  "type": "https://api.twitter.com/2/problems/unsupported-authentication",n' +
    '  "status": 403n' +
    '}'
}

Even though I have successfully have the oauth_access_token and oauth_access_secret as described in https://developer.twitter.com/en/docs/authentication/oauth-1-0a/obtaining-user-access-tokens
Below is my code snippet to send the request;

// server.js
app.get('/api/twitter/temp/profile', async (req, res) =>{
  const { oauth_access_token, oauth_access_token_secret } = access_tokens[tmp_token]; 
  try {
    // const ids = req.query.ids.join()
    const ids = req.query.ids
    console.log("ids "+ids)
    console.log(oauth_access_token, oauth_access_token_secret)
    const response = await oauth.sendRequest({
      method: 'get',
      url: `https://api.twitter.com/2/users?ids=${ids}`,
      oauth_access_token,
      oauth_access_token_secret
    })
    console,log(response)
    res.json({message: 'ok'})
  } catch (error) {
    console.log(error)
  }
})

The library that I used to send the request to twitter (taking care of headers etc) is https://github.com/ciaranj/node-oauth/blob/a7f8a1e21c362eb4ed2039431fb9ac2ae749f26a/lib/oauth.js#L486, so the oauth in my server.js is a wrapper of that library etc.

Google Apps Script – use Google Drive pdf with PDF-lib.js

Background:
I am try to fill in a pdf file that:
a) has form fields.
b) that is stored on Google Drive.

with data that is stored in Google spreadsheet.

I am using:

  1. Google Apps Script.
  2. HtmlService
  3. PDF-lib.js in a htmlOutput object generated from a htmlTemplate.

The work flow is:

  1. The showModalDialog_downloadFilledPDFform_NAMOFFORM() function is called from a menu.

The function is:

function showModalDialog_downloadFilledPDFform_NAMOFFORM() {
  var pdf_template_file_url = getPDFfileURL("form1.pdf");
  var htmlTemplate = HtmlService.createTemplateFromFile('downloadFilledPDFformHTML');
  
  htmlTemplate.dataFromServerTemplate = { pdf_template_file: "form1.pdf", pdf_template_file_url: pdf_template_file_url };
  
  var htmlOutput = htmlTemplate.evaluate();
  htmlOutput.setWidth(648.1);
  htmlOutput.setHeight(286.300)
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Download filled PDF');
}

The url that is passed to the htmlTemplate is generated by: “fillPDFForm.gs”

function: fillPDFForm.gs:

var pdfFileNamesAndIDs = [ ]
  pdfFileNamesAndIDs.push(["form1.pdf", "1y8F5NgnK50mdtWSR6v1b8pELsbbBJert"])
  pdfFileNamesAndIDs.push(["form2.pdf", "1B4BOaI-BqFmhmnFx7FaT-yys-U0vkYKz"])
  pdfFileNamesAndIDs.push(["form3.pdf", "17LrJpRA5oBZBqw-2du1H74KxWIX55qYC"])

function getPDFfileURL(fileName) {
  var documentID = "";
  for (var i in pdfFileNamesAndIDs) {
    //console.log(pdfFileNamesAndIDs[i][0]);
    if (pdfFileNamesAndIDs[i][0] == fileName) {
      documentID = pdfFileNamesAndIDs[i][1];
      console.log("documentID: " + documentID);
    }
  }

  var documentFile = DriveApp.getFileById(documentID);
  var documentURL = documentFile.getDownloadUrl();
  Logger.log("documentURL = "+documentURL);

  return documentURL;
}

The Problem:
The URL generated by getPDFfileURL() doesn’t work in the html file generated in showModalDialog_downloadFilledPDFform_NAMOFFORM().

The error in Chrome dev console is:

[email protected]:15 Uncaught (in promise) Error: Failed to parse PDF document (line:0 col:0 offset=0): No PDF header found
    at e [as constructor] ([email protected]:15:189222)
    at new e ([email protected]:15:190065)
    at e.parseHeader ([email protected]:15:401731)
    at e.<anonymous> ([email protected]:15:400782)
    at [email protected]:15:1845
    at Object.next ([email protected]:15:1950)
    at [email protected]:15:887
    at new Promise (<anonymous>)
    at i ([email protected]:15:632)
    at e.parseDocument ([email protected]:15:400580)

The basic concept for the html page (shown as a modal dialog box), came from: https://jsfiddle.net/Hopding/0mwfqkv6/3/

I have replicated the contents of the html file on my testing webserver. The server has 3 files: index.html, stykesheet.css and form1.pdf

The pdf (on the web server) is the same pdf file that is stored on Google drive.

On my server the following works:

  1. if I use the pdf file that is in the same folder as the html and css files, a filled pdf is offered for download.

…but the following doesn’t work:

  1. if I use the same URL that is generated by getPDFfileURL(), nothing happens and no filled pdf is offered for download.

So the question is:
How do I generate the correct URL (for the pdf file stored in Google Drive), so it can then be used by PDF-lib.js (in the htmlTemplate)?

Jest: delay before query or before test

Trying to figure out how to run query via axios after a timeout.

beforeEach(() => { jest.useFakeTimers() })
afterEach(() => { jest.useRealTimers() })
test('timeout before query', () => {
  const body = {...}
  const config = {...}
 
  console.log('timeout start')
  await setTimeout(async () => {
    console.log('timeout end')
    console.log('running query')
    const response = await axios.post(`${HOST}/api/export`, body, config)
    expect(response.status).toBe(200)
  }, 10000);
  jest.advanceTimersByTime(20000)
)}

Code executes immediately. What a hack should be written to make it sleep for a while?

Way to listen for audio events on stream? peerjs

I’m using Peer.js for sharing streams across users, I want to listen for the audio events like mic on, off.
And also is there a way to check whether the user is speaking or he is silent.

This is how I’m muting when user click on mute button,

const audioTrack = stream.getAudioTracks()[0];
audioTrack.enabled = false;

I want to listen for this event in all other users to show that he is muted his mic.

How do I view movies in descending order of average score? django

What we want to achieve.

I want to display the score (stars) of a movie in descending order.

Present condition

The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html.

I want to ask a question.

And if score is selected, how can I make it appear in descending score order?
data = requests.get (f “https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US”).
Now you can get the information of tv.

def index(request):
    movie = reversed(Movie.objects.order_by('stars'))
    tv    = reversed(TV.objects.order_by('stars'))
    context = {
        "movie": movie,
        "tv"   : tv,
    }
    return render(request, 'Movie/index.html', context)
class Movie(models.Model):
    id = models.CharField(primary_key=True, editable=False,
                          validators=[alphanumeric],max_length = 9999)
    stars = models.FloatField(
                    blank=False,
                    null=False,
                    default=0, 
                    validators=[MinValueValidator(0.0),
                     MaxValueValidator(10.0)]
                     )
    def get_comments(self):
        return Comment_movie.objects.filter(movie_id=self.id)
    
    def average_stars(self):
        comments = self.get_comments()
        n_comments = comments.count()

        if n_comments:
            self.stars = sum([comment.stars for comment in comments]) / n_comments
        else:
            self.stars = 0
        return self.stars
class TV(models.Model):
    id = models.CharField(primary_key=True, editable=False,
                          validators=[alphanumeric],max_length = 9999)
    stars = models.FloatField(
                    blank=False,
                    null=False,
                    default=0, 
                    validators=[MinValueValidator(0.0),
                     MaxValueValidator(10.0)]
                     )
    def get_comments(self):
        return Comment_tv.objects.filter(tv_id=self.id)
    
    def average_stars(self):
        comments = self.get_comments()
        n_comments = comments.count()

        if n_comments:
            self.stars = sum([comment.stars for comment in comments]) / n_comments
        else:
            self.stars = 0
        return self.stars
          

class Comment_movie(models.Model):
    comment     = models.TextField(max_length=1000)
    stars       = models.FloatField(
                     blank=False,
                     null=False,
                     default=0, 
                     validators=[MinValueValidator(0.0),
                     MaxValueValidator(10.0)]
                  )

    user        = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    movie       = models.ForeignKey(Movie, on_delete=models.CASCADE)
    created_at  = models.DateTimeField(default=datetime.now)
    updated_at  = models.DateTimeField(auto_now=True)
    class Meta:
        unique_together = ('user', 'movie')
        indexes = [
        models.Index(fields=['user', 'movie']),
        ]
    
class Comment_tv(models.Model):
    class Meta:
        unique_together = ('user', 'tv',)
    
    comment     = models.TextField(max_length=1000)
    stars       = models.FloatField(
                     blank=False,
                     null=False,
                     default=0, 
                     validators=[MinValueValidator(0.0),
                     MaxValueValidator(10.0)]
                  )

    user        = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    tv          = models.ForeignKey(TV, on_delete=models.CASCADE)
    created_at  = models.DateTimeField(default=datetime.now)
    updated_at  = models.DateTimeField(auto_now=True)
    class Meta:
        unique_together = ('user', 'tv')
        indexes = [
        models.Index(fields=['user', 'tv']),
        ]

{% extends "base.html" %}
{% block content %}
    <h2>Trending</h2>
    <div class="input-group mb-3">
        <select class="form-select" id="media_type">
          <option selected>All Trending Media Types</option>
          <option value="movie">All Trending Movies(day)</option>
          <option value="tv">All Trending TV Shows(day)</option>
          <option value="person">All Trending Persons(day)</option>
     <option value="score">score</option>     
        </select>
    </div>
    
    <div id="trendings" class="row">

    </div>
    {% load static %}
    <script src="{% static 'js/Movieindex.js' %}"></script>
    
{% endblock %}
fetchTrendingResults("all", "week")

        var mediaType = document.getElementById("media_type")
        mediaType.addEventListener("change", function(event) {
            fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day")
        })

        function fetchTrendingResults(media_type, time_window) {
            var trendingDiv = document.getElementById("trendings")
            trendingDiv.innerHTML = ""

            fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json"
                }}
                // todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。
                )
            .then(res => res.json())
            .then(data => {
                for (let i=0; i<data.results.length; i++) {
                    var mainDiv = document.createElement("div");
                    mainDiv.setAttribute("class", "card");
                    mainDiv.setAttribute("style", "width: 18rem;");
                    var img = document.createElement("img");
                    img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path);
                    img.setAttribute("class", "card-img-top");
                    img.setAttribute("alt", "...");
                    var body = document.createElement("div");
                    body.setAttribute("class", "card-body");
                    var title = document.createElement("h5");
                    title.setAttribute("class", "card-title");
                    if (data.results[i].name) {
                        title.innerHTML = data.results[i].name;
                    } else {
                        title.innerHTML = data.results[i].title;
                    }
                    //var text = document.createElement("p");
                    //text.setAttribute("class", "card-text");
                    //text.innerHTML = data.results[i].overview;
                    var link = document.createElement("a");
                    link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/");
                    link.setAttribute("class", "btn btn-primary");
                    link.innerHTML = "View Details";
                    body.appendChild(title);
                    //body.appendChild(text);
                    body.appendChild(link);
                    mainDiv.appendChild(img);
                    mainDiv.appendChild(body);
                    document.getElementById("trendings").appendChild(mainDiv);
                }
            })
        }

Reading length of on of the object in a Multiple objects Json Array using Javascript

All I need is to select a region from the first drop down then it will fill the second dropdown with the data from the Json array accordingly.

I facing an issue with reading the length of the selected region array after selecting the region from the drop-down. I get undefined due to the length, but when I remove the .length property, I get the array correctly.

const myJSON = '[' +
  '{"المنطقة الشرقية":[' +
  '{ "cityName":"الدمام","deliveryTime":"1" },' +
  '{ "cityName":"الخبر","deliveryTime":"1" },' +
  '{ "cityName":"القطيف","deliveryTime":"1" },' +
  '{ "cityName":"صفوى","deliveryTime":"1" },' +
  '{ "cityName":"سيهات","deliveryTime":"1" },' +
  '{ "cityName":"عنك","deliveryTime":"1" },' +
  '{ "cityName":"الظهران","deliveryTime":"1" },' +
  '{ "cityName":"الجبيل","deliveryTime":"1" },' +
  '{ "cityName":"الهفوف","deliveryTime":"1" },' +
  '{ "cityName":"رأس تنورة","deliveryTime":"1" },' +
  '{ "cityName":"بقيق","deliveryTime":"1" },' +
  '{ "cityName":"المبرز","deliveryTime":"1" },' +
  '{ "cityName":"رحيمة","deliveryTime":"1" },' +
  '{ "cityName":"الأحساء","deliveryTime":"1" },' +
  '{ "cityName":"الخفجي","deliveryTime":"1" },' +
  '{ "cityName":"النعيرية","deliveryTime":"1" },' +
  '{ "cityName":"تاروت","deliveryTime":"1" }' +

  ']},' +
  '{"المنطقة الوسطى":[' +
  '{ "cityName":"الرياض","deliveryTime":"" },' +
  '{ "cityName":"الخرج","deliveryTime":"" },' +
  '{ "cityName":"بريدة","deliveryTime":"" },' +
  '{ "cityName":"عنيزة","deliveryTime":"" },' +
  '{ "cityName":"الرس","deliveryTime":"" },' +
  '{ "cityName":"المجمعة","deliveryTime":"" }' +

  ']}' +
  ']';
const myObj = JSON.parse(myJSON);
var regions = document.getElementById("m_continent");
// Optional: Clear all existing options first:
regions.innerHTML = " <option value='-1'>اختر منطقة التوصيل</option>";
// Populate list with options:
var j = 0;
var allCities;
Object.keys(myObj).forEach(function(key) {
  var value = Object.getOwnPropertyNames(myObj[key]);
  regions.innerHTML += "<option value="" + j++ + "">" + value + "</option>";
});

function fillCities(val) {
  var cities = document.getElementById("m_cities");
  var region = regions.value;
  cities.innerHTML = " <option value='0'>اختر مدينة التوصيل</option>";
  var allCities = myObj[region];
  console.log(allCities.length);

  for (var i = 0; i < allCities.length; i++) {
    var city = allCities[i];
    console.log(city);
    cities.innerHTML += "<option value="" + city + "">" + city + "</option>";
  }

}
<!DOCTYPE html>
<html>

<body style="direction:rtl">

  <h2>مدن وأوقات التوصيل</h2>
  <p>يمكنك تقدير وقت وصول طلبك لمدينتك</p>
  <label for="m_continent">اختر منطقتك</label>
  <select id="m_continent" onchange="fillCities(this.value)">
  </select>
  <br>
  <label for="m_cities">اختر مدينتك</label>
  <select id="m_cities">
    <option value="0">اختر المنطقة أولا</option>
  </select>
  </div>
  <p id="delivery-time"></p>


</body>

</html>

All I want is to find the length of the selected array.

JavaScript latest method of validating email

I’ve been reading this article for quite a while but it seems most of the answers are outdated, 10+ years ago.

How can I validate an email address in JavaScript?

The below code is from w3resource https://www.w3resource.com/javascript/form/email-validation.php , Does this enough and still works?

/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/

Or do you have any better or more modern way of validating email?

Fetch data from another column to make if statement, and add some data in another column using columndefs in jquery

here my table look likehow can i do in columndefs like this if column equal to ‘MIA up MTD’, and i can add some data in entire row of ‘MIA up to MTD’ start column MIA 0 until column MIA 5.. below i attach some picture

"columnDefs": [

                    {
                        var accPaidPercentColumn = [1,2];
                        "targets": accPaidPercentColumn,
                        "render": function(data, type, row, meta) {
                               

                                if (data == 'MIA up MTD') {

                                    if (meta == 2) {
                                        var percentage = data + '<div class="progress"><div class="progress-bar""></div></div>';
                                        return percentage;
                                    }
                                    

                                }

                                else { 
        
                                   var percentage = data    + '';
                                   return percentage;

                                }

                        }
                    }
                ]