validate phone number length using jquery not working

i am trying to validate phone number length using jquery, when user start typing itself it should display, i did the following code:

function validatePhone(phone) {
  if (phone.value.length <= 10 && phone.value.length >= 5) {
    let
    var = 'Yes';
    return var;
  } else {
    let
    var = 'No';
    return var;
  }
}

function validate() {
  let result1 = $("#result1");
  let phone = $("#phone").val();
  result1.text("");


  if (validatePhone(phone)) {
    result1.text(var);
    result1.css("color", "green");
  }
  return false;
}
jQuery(function($) {
  $("#phone").on("input", validate);
});
<input type="number" class="form-control"  id="phone" name="phone">
<span class="label">Phone Number<span style="color:red">*</span> <span id="result1"></span></span>

however this doesnt work, can anyone please tell me what is wrong in here, thanks in advance

How to write a js function that updates a number once a month

I’d like to create a script that updates a number on my website monthly. I’ve made it work with miliseconds. But how do I do it with a month. It’s something with the setInterval, righ?


let m2 = document.createElement("h2");


function naturfonden() {
    m2.innerHTML = "240";
    let parent = document.querySelector("#menu-item-2472");
    // I'm placing the number in the menu
    parent.appendChild(m2);

    setInterval(displayM2, 5000);

    function displayM2() {
      let numberOfM2 = parseInt(m2.innerText);
      numberOfM2 += 10;
        console.log(typeof(numberOfM2));
        console.log(numberOfM2);
        m2.innerHTML = numberOfM2;
    }  
}

naturfonden();

I tried following a tutorial and succeeded but I couldn’t find one that fitted my need.

Error ‘undefined function’ when calling an imported function from a JavaScript module file in an HTML file

I am encountering an issue where I have defined a function in a JavaScript file and imported it into an HTML file using the ‘type=”module”‘ attribute. However, when I try to call the imported function from the HTML file, it throws an ‘undefined function’ error. I have verified that the function is indeed defined in the JavaScript file. How can I resolve this issue and successfully call the imported function in my HTML file?

I have this “pagLibro.html” where I generate a bookpage, in its body I actually only have the navbar and the shopping cart

<!DOCTYPE html>
<html lang="es">
  <head>
      <script type="module">
        import { cargaLibro } from './js/libroPropio.js';
        window.cargaLibro = cargaLibro;
      </script>     
      <script type="module" src="./js/libroPropio.js"></script>
      <script src="./js/perfil.js"></script> 

and the rest of the body it’s completed automatically from a javascript libroPropio.js, where I do a few things to do a bookpage depending on which book you click on in a main page. The problem is in the function cargaLibro(), I’ve tried everything to make it work but it still says Uncaught ReferenceError: cargaLibro is not defined at HTMLButtonElement.onclick (pagLibro.html?id=3:1:1)


function renderBook(book) {
    let libroHtml = "<br><br><br><br>";
    libroHtml = `
    <div class="container mt-5 mb-5">
         <div class="card">
            <div class="row g-0" id="${book.id}">
               <div class="col-md-6 border-end" id="imagen">
                  <div class="d-flex flex-column justify-content-center">
                     <div class="main_image">   <img src="${book.portada}" id="mainProductImage" width="350" alt="Portada del libro"> </div>
                     <div class="thumbnail_images">
                        <ul id="thumbnail">
                           <li><img onclick="cambiaImagen(this)" src="${book.portada}" width="70"></li>
                           <li><img onclick="cambiaImagen(this)" src="${book.contraportada}" width="70"></li>
                        </ul>
                     </div>
                  </div>
               </div>
               <div class="col-md-6" id="datos">
                    <div class="p-3 right-side">
                        <div class="d-flex justify-content-between align-items-center" id="titulo">
                            <h3>${book.titulo}</h3>
                        </div>
                        <div class="d-flex justify-content-between align-items-center" id="autor">
                            <h5>${book.autor}</h5>
                        </div>             
                        <div class="mt-2 pr-3 content" id="texto">
                            <h6>${book.descripcion}</h6>
                        </div>
                        <h3>${book.precio}€</h3>
                        <div class="buttons d-flex flex-row mt-5 gap-3" id="boton">
// THE PROBLEM IS IN THIS LINE, AND I DON'T KNOW HOW TO SOLVE IT, IN CARGALIBRO
                          <button onclick="cargaLibro(${book.id})" class="btn btn-dark" id="carga">Añadir al carrito</button>
                          <button onclick="mostrarFormulario()" class="btn btn-primary">Añadir comentario</button>
                          </div>                                                  
                    </div>
                </div>
            </div>
        </div>
    </div>
  `;

libroHtml += `<h1 class="titulo">Comentarios:</h1>
<div id="formularioComentario" style="display: none;">
<h3>Añadir Comentario</h3>
<form id="comentarioForm">
  <div>
    <label for="usuario">Usuario:</label>
    <input type="text" id="usuario" value="${username}">
  </div>
  <div>
    <label for="valoracion">Valoración:</label>
    <select id="valoracion" required>
      <option value="1">1 Estrella</option>
      <option value="2">2 Estrellas</option>
      <option value="3">3 Estrellas</option>
      <option value="4">4 Estrellas</option>
      <option value="5">5 Estrellas</option>
    </select>
  </div>
  <div>
    <label for="descripcion">Descripción:</label>
    <textarea id="descripcion" required></textarea>
  </div>
  <button type="submit">Enviar Comentario</button>
</form>
</div>
`;

  if (book.comentarios && book.comentarios.length > 0) {
    for (let i = 0; i < book.comentarios.length; i++) {
        const comentario = book.comentarios[i];
        libroHtml += `
        <div class="container mt-4">
            <div class="row"> 
                <div class="col-md-12">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header border-0 pb-0">
                            <h5 class="card-tittle">${renderValoracion(comentario.valoracion)}</h5>
                        </div>
                        <div class="card-body pt-2">
                            <small class="card-subtitle mb-2 text-muted">${comentario.usuario}</small>
                            <p class="card-text">${comentario.descripcion}</p>
                        </div>
                    </div>
                </div>
            </div>  
        </div>
      `;
    }
  } else {
    libroHtml += `
      <div class="container mt-4">
        <div class="row">
          <div class="col-md-12">
            <div class="card border-0 shadow-sm text-center">
              <div class="card-body">
                <h2>No hay comentarios para este libro</h2>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  }

  document.getElementById("countResults").innerHTML = libroHtml;
}

the function is this one:

export function cargaLibro(libroIdDiv){
  var libroId = libroIdDiv.id
  var libro = listProducts.find(function (book) {
    return book.id == libroId
  })
  var cantidad = 0

  if (carritoMap.size == 0) {
    cantidad = 1
    carritoMap.set(libro.id, cantidad)
    console.log("PRIMERO")
  } else {
    var igual = false
    for (let [id, cant] of carritoMap.entries()) {
      if (libro.id === id) {
        cantidad = cant + 1
        carritoMap.set(libro.id, cantidad)
        igual = true
        console.log("IGUALES")
      }
    }
    if (igual == false) {
      cantidad = 1
      console.log("DISTINTOS")
      carritoMap.set(libro.id, cantidad)
    }

  }

I’m using it as a module because I need to import DBManager.js to connect to a Firebase database and that’s when the onclick buttons started not working. How can I fix this?

I’ve tried doing window.CargaLibro = cargaLibro, declaring the function as a export function, but none of this is working.

In the script tag, type = module question

The part defined as type = “module” in the script tag performs well the first time after the server comes up.

However, if you refresh or search with a button to retrieve data in an asynchronous manner and bind it, it cannot be performed. They all call the same function and use it.

I wish you a strong refresh or clearing of your spit. Unconditional service must be restarted to perform the initial 1 well

If there is someone who knows this well that the rest will not be able to do activities, I would really appreciate it if you could let me know.

strong refresh or clearing cache

how to résolvez issue react js next-routes [closed]

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^16.0.0" from the root project
npm ERR!   peer react@"^15.4.2 || ^16" from [email protected]
npm ERR!   node_modules/next-routes
npm ERR!     next-routes@"1.4.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^18.2.0" from [email protected]
npm ERR! node_modules/next
npm ERR!   next@"^13.4.1" from the root project
npm ERR!   peer next@">=2" from [email protected]
npm ERR!   node_modules/next-routes
npm ERR!     next-routes@"1.4.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! C:UsersHPAppDataLocalnpm-cache_logs2023-05-11T07_50_18_529Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersHPAppDataLocalnpm-cache_logs2023-05-11T07_50_18_529Z-debug-0.log

solution pour ressoudre ce probleme ?

Uncaught ReferenceError: jwplayer is not defined in React JS

I am trying to play jwplayer videos in my react project, and as documentation suggested I am adding the below code in my public index.html file:

<script
      src="http://localhost:3000/jwplayer/jwplayer.js"
      type="text/jsx"
    ></script>
    <script type="text/javascript">
      jwplayer.key =
        "+1bANyiZkLQznP2yV8ky+2NgQqiQmMg3/Sc0tJdhWUPtP51/8zGnxqqw=";
</script>

But getting the above refernce error. Is there any way i can resolve this issue or if any one has integrated the Self-hosted jwplayer in their react js projects.

Display a button after promises are resolved

I have a javascript function inside which i have 3 api calls with promises. How can I display a button when all promises are resolved.

I had to make different function which i execute after first function. But that only increases buttons and functions in my code.

Node 18 JavaScript heap out of memory

ok, so heres a weird scenario that happens:

-We have an service that runs on node 14 and we want to update it to 18 but we get constantly 'JavaScript heap out of memory', when you look online it just says to put more ram using node options, this however doesn’t work.

-There is a workaround that we found is that if we do npm i with node 14 and then npm i again it will rebuild the lock file and everything is ok as it should.

-There is also a workaround that you can do npm i --legacy-peer-deps

So my question is what can i do to avoid this? is it one of the packages that is screwing this up? if so how can i find the package thats causing this issue? and why would it cause it?

regular expression to detect dynamic Id in path

I want to detect where url contains dynamicId or not after courseId.

for example /platform/6323/courses/823273/subject-settings/subject/233224/lesson. In this path there is dynamic id 233224 after courseId 823273. How can I detect this with regex. This prefix will always there /platform/6323/courses/823273 but after that anything can be there.

for example:

/platform/6323/courses/823273/subjects/233224/insights
/platform/3712/courses/77850/projects/15148/progress
/platform/3712/courses/77850/projects/attendance/attendance-settings/15148/nodeType/71627/info

this all above example should considered as dynamic route. as there exist id after course id.

and below route are considered as non-dynamic route as there is no id after course id.

/platform/3712/courses/77850/projects/attendance/attendance-settings
/platform/3712/courses/77850/attendance/insights

Want to have regex function for this problem.

Returning a PartialView with C# Razor Pages is causing an Error: Multiple constructors

I am trying for hours to return a Table as PartialView with the help of C# Razor Pages.
First i got the error the returning model is not equal to the expected model.
I changed the view model and the error was gone.
Now i got the Error:

InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'System.Collections.Generic.List`1[DantronikOrganizer.Data.Models.UserVacationEntity]'. There should only be one applicable constructor.

I start from the beginning:
I created a Index Page to show users there vacation requests in a table, but if they choose to delete an entry from the table, the entire page would be reloaded. So i though why not using ajax to solve this problem.

I deleted the table in my index page and created a new one in a _TableView.
Now an ajax request should load the view from _TableView into my index page.
Now when a user is deleted an entry from the table, only the table would be reloaded.
Thanks to the new PartialView.

I asked ChatGPT a lot about my problem, but even ChatGPT is not understanding why i get this error.

My Index View

@page
@model DantronikOrganizer.Pages.Vacation.IndexModel

@{
    ViewData["Title"] = "Urlaubsanträge";
}

<h1>Übersicht - Urlaubsanträge</h1>
<hr />

<p>
    <a class="btn btn-success" asp-page="VacationRequest">Urlaub beantragen</a>
</p>

<form>
    <div class="input-group mb-2 w-25">
        <input id="yearFilter" asp-for="@Model.FilterYear" class="form-control" placeholder="Nach Jahr filtern" aria-label="Filer by Year" aria-describedby="btnFilter">
        <button class="btn btn-outline-secondary" type="submit" id="btnFilter">Filtern</button>
    </div>
    <span asp-validation-for="@Model.FilterYear" class="text-danger"></span>
    <div class="form-check mb-2">
        <input id="approvedFilter" asp-for="@Model.FilterIsApproved" class="form-check-input" />
        <label class="form-check-label" asp-for="@Model.FilterIsApproved"></label>
    </div>
</form>
<hr />

<div class="row">
    <div class="col-lg-6">
        <h6>Ausgewähltes Jahr: </h6>
        <span class="text-primary">Urlaubstage: | Bisher genutzte: | Verfügbare: </span>
    </div>
</div>
<div id="partialViewContainer"></div>

<!--Modal Window to delete an entry in the table-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">Eintrag löschen</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Möchten Sie wirklich den Eintrag löschen?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Abbrechen</button>
                <button type="button" class="btn btn-primary" id="deleteButton">Löschen</button>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <script>
        function showToast(message) {
            Toastify({
                text: message,
                duration: 5000,
                gravity: "top",
                position: "center",
                style: {
                    background: "#ff5722"
                },
                stopOnFocus: true
            }).showToast();
        }

        $(document).ready(function () {
            loadPartialView();
            $('#yearFilter, #approvedFilter').change(function () {
                loadPartialView();
            });
        });

        function loadPartialView() {
            var year = $('#yearFilter').val();
            var isApproved = $('#approvedFilter').is(':checked') || false;
            $.ajax({
                url: '@Url.Page("/Vacation/_TableView", "TableView")',
                data: { year: year, isApproved: isApproved },
                type: 'GET',
                success: function (data) {
                    $('#partialViewContainer').html(data);
                }
            });
        }

        function deleteVacation(id) {
            var token = $('input[name="__RequestVerificationToken"]').val();
            $('#deleteModal').modal('show');
            $('#deleteButton').on('click', function () {
                if (confirm("Möchten Sie wirklich den Eintrag löschen?")) {
                    $.ajax({
                        type: "POST",
                        url: "/Vacation/Delete?handler=delete",
                        data: { id: id, __RequestVerificationToken: token },
                        headers: { "RequestVerificationToken": token },
                        success: function (response) {
                            if (response.success) {
                                showToast(response.message);
                                loadPartialView();
                            }
                        },
                        error: function (response) {
                            if (response.error) {
                                showToast(response.message);
                            }
                        }
                    });
                    $('#deleteModal').modal('hide');
                }
            });
        }
    </script>
}

My PartialView Controller

using DantronikOrganizer.Areas.Identity.Data;
using DantronikOrganizer.Data.Interfaces;
using DantronikOrganizer.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DantronikOrganizer.Pages.Vacation
{
    public class _TableView : PageModel
    {
        private readonly IUserVacation _service;
        private readonly UserManager<ApplicationUser> _userManager;
        public List<UserVacationEntity> UserVacationList { get; set; }
        public _TableView(IUserVacation service, UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
            _service = service;
        }

        public async Task<IActionResult> OnGetTableView(int year, bool isApproved)
        {
            var user = await _userManager.GetUserAsync(User);
            UserVacationList = await _service.GetUserVacationByUser(user.Id);

            if (!string.IsNullOrEmpty(year.ToString()))
            {
                UserVacationList = UserVacationList.Where(u => u.DtFrom.Year == year).ToList();
            }

            if (isApproved)
            {
                UserVacationList = UserVacationList.Where(x => x.IsApproved).ToList();
            }
            return Partial("_TableView", UserVacationList);
        }
    }
}

My Partial View

@page
@model List<DantronikOrganizer.Data.Models.UserVacationEntity>
<table class="table table-hover">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(m => m[0].DtFrom)
            </th>
            <th>
                @Html.DisplayNameFor(m => m[0].DtUntil)
            </th>
            <th>
                @Html.DisplayNameFor(m => m[0].DaysRequested)
            </th>
            <th>
                @Html.DisplayNameFor(m => m[0].IsApproved)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null && Model.Any())
        {
            @foreach (var item in Model)
            {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.DtFrom)</td>
                <td>@Html.DisplayFor(modelItem => item.DtUntil)</td>
                <td>@Html.DisplayFor(modelItem => item.DaysRequested)</td>
                <td>@Html.DisplayFor(modelItem => item.IsApproved)</td>
                <td>
                    <a class="btn btn-primary" asp-page="./Edit" asp-route-id="@item.Id">Bearbeiten</a> |
                    <a class="btn btn-primary" asp-page="./Details" asp-route-id="@item.Id">Details</a> |
                    <button class="btn btn-danger" onclick="deleteVacation(@item.Id)">Löschen</button>
                </td>
            </tr>
            }
        }
        else
        {
        <tr>
            <td colspan="5">No vacation entries found.</td>
        </tr>
        }
    </tbody>
</table>

Fetching data using ajax in a table

<!DOCTYPE html>
<html>
  <head>
    <title>Fetch data from API and display in table using AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <h1>Data</h1>
    <table id="table" border="1"></table>

    <script>
      function load(){
        fetch("https://gorest.co.in/public/v2/users")
          .then(result => result.json)
          .then(json => show(json)) }
      function show(data){
      let table = document.getElementById('table');
      for(let i=0; i< data.length; i++){
        let obj = data[i];
        console.log(obj);
        let row = document.createElement('tr');
        let name = document. createElement('td');
        id.innerHTML = obj.
        row.appendChild(name)
        table.appendChild(row)
  }


}
    </script>
  </body>
</html>

I need to fetch data from a url. I have to present it in a table. First I only need to display username with a button “view more”. When view more will be clicked I have to fetch data from another api related to that particular username .I have written few line of code but they are not working. Any suggestionns? your text

Flow Based Visual Programming in Django

I am working with a Django Application for E-Commerce, where I have to build a visaul programming (Flow Based) feature. I came across two JS libraries RETE.JS and NODE-RED.

Node-RED is pretty powerfull tool, but it seem pretty difficult to integrate with Django application, as it is a node app. Also, I tried running it on port 1880 and loading it as <iframe>, which worked. But, still creating a lot of e-commerce custom nodes in NODEJS is big deal for me. (I am more into Python, Jquery, Normal Js but not in NODE.JS)

For retejs, there is no sidebar list of flow controls, meta fields for controls, like Node-Red already have.

Can you suggest some Open-Source JS based library which you help me develope some feature like in image attached. (Attached image is screenshot of feature from some company’s platform)

enter image description here

How to view (preview) excel file after upload in reactjs

When I upload excel file and convert it to url blob using URL.createObjectURL() and a button when onClick it will show my excel file. But instead of watching it download it.

here is my code:

const onUploadFile1 = (e) => {
    const file = e.target.files[0]

    setFile(file)
}

const onClickToView = () => {
    window.open(URL.createObjectURL(file), '_blank', 'noreferrer')
}

(*)I have used libraries to convert like xlsx, react-excel-renderer…but it’s not what I want because it breaks the layout of the file or when in excel there is an image it doesn’t display.

Can someone help me, the end goal I want is to view the excel file after uploading.
Thanks.

commit or dispatch inside a callback [duplicate]

I have a function in my vue/nuxt project to authorize a payment method, and inside de callback I need to execute a commit and a dispatch but the syntax apparently is not correct.
Any help will be appreciated.

myFunction () {
      window.client.Payments.authorize({
        payment_method_category: 'payments'
      }, {
        purchase_country: 'ES',
        purchase_currency: 'EUR',
        locale: 'es-ES',
        billing_address: {
        },
        shipping_address: {
        },
      },
      function (res) {
        if (res.approved) {
**        this.$store.commit('checkout/setMyFunctionAuthorizationToken', res.authorization_token)
          this.$store.dispatch('checkout/finish')
**        }
      })
    },

I can’t use the ‘this.$store’ but I don’t how to do it.

JS includes() returning partial matches

I have an string of numbers that we are comparing to ids in a json file with javascript to create a list of favorites. I am using includes() to test if the tourid in the json file is also in the string.

The issue shows up with larger numbers in the array. If the list contains 34, then the output shows only the details for tourid 34, but if 134 is in the list, then the output shows both tourid 34 and 134. I have also tried indexOf() with similar results.

Is there a way to force includes() to only go with exact matches?

The script is below (and yes it is in a worker script hence the postMessage ending):

function getMyLst(mylst) {
  // build nav list of based on myList array

  // check if mylst is empty of numbers
  if (mylst === '') {
    let myLstStr = 'rmvml|0';
    postMessage(myLstStr);
  }
  else {

    let xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        var myLstStr = 'mylst|';
        var lstCnt = 0;
        var daLst = '';
        var clipList = '';
        data = JSON.parse(this.responseText);
        // loop through check if in mylst then build string
        for (let i = 0; i < data.length; i++) {
          if (mylst.includes(data[i].tourid)) {
            myLstStr += '<a href="'+data[i].url+'">'+data[i].tourname+'</a><br>';
            lstCnt++;
            daLst += (data[i].tourid)+',';
            clipList += data[i].tourname+' - '+data[i].url+'n';
          }
        }
        myLstStr += '|'+lstCnt+'|'+daLst.slice(0, -1)+'|'+clipList;
        postMessage(myLstStr);
      } 
    };

    xmlhttp.open("GET", dturl, true);
    xmlhttp.send();

  }
}

The worker onmessage function, with the value of mylst as sent to the worker as a comma separated string: mylst|146,57,134

onmessage = function (e) {

  // Determine worker function from first variable
  // strip first value before "|"
  let msg = e.data[0];
  var val = msg.split('|');

  // GO get myList data
  if (val[0] === 'mylst') {
    var mylst = val[1] ;
    getMyLst(mylst);
  }
  // end myList section