Validador Rut/Run chileno

/*Tengo esos 2 campos donde se debe ingresar el rut y el dv. como seria el js para una validación de rut existente.
*/

<div class="form-group mb-4">
<input type="text" name="rut" id="rut" class="form-control" placeholder="Rut" maxlength="8" minlength="7" pattern="[0-9]*" title="Debe ingresar valores númericos" required/>
<label class="form-label" for="rut"></label>
</div>   

<div class="form-group text-center mb-4">
<input type="text" name="dv" id="dv" class="form-control" maxlength="1" pattern="[1-9kK]*" title="Solamente se permite Números, SI SU RUT TERMINA CON 0 INGRESAR K" placeholder="Dv" required/>
<label class="form-label" for="dv"></label>
</div>

/*
Con este codigo logro me funcione el validador de cierta manera el problema es que tampoco me permite la creacion de usuarios con rut existentes
*/

function validarRut(rut, dv) {
    if (rut.trim() === "" || !/^[0-9]+[-|‐]{1}[0-9kK]{1}$/.test(rut)) {
        return false;
    }

    rut = rut.replace(/./g, "").replace("-", "");

    var splitRut = rut.split("-");
    var cuerpoRut = splitRut[0];
    var dvUsuario = splitRut[1];

    var suma = 0;
    var multiplo = 2;

    for (var i = cuerpoRut.length - 1; i >= 0; i--) {
        suma += parseInt(cuerpoRut.charAt(i)) * multiplo;
        multiplo = multiplo < 7 ? multiplo + 1 : 2;
    }

    var dvEsperado = 11 - (suma % 11);

    dvEsperado = (dvEsperado === 11) ? 0 : (dvEsperado === 10) ? "K" : dvEsperado.toString();

    return dvEsperado.toUpperCase() === dv.toUpperCase();
}

document.addEventListener("DOMContentLoaded", function() {
    var form = document.querySelector("form");

    form.addEventListener("submit", function(event) {
        var rutInput = document.getElementById("rut");
        var dvInput = document.getElementById("dv");

        var rutValue = rutInput.value;
        var dvValue = dvInput.value;

        if (!validarRut(rutValue, dvValue)) {
            alert("RUT Inválido");
            event.preventDefault();
        }
    });
});

How to avoid page reload in php post form submission

  • here in the menu page i have form which is includ the form of menu items and add to favourites button (wishlist) when i add it to the favourites it add in the database fine, but it reload the page i tried a lot and i’m still trying, need some help. Thanks

menu.php

<div class="wrapper wrapp-menu-item">
                <div class="menu-item flex-row zoom-gallery">
                    <?php
                    $select_products = $conn->prepare("SELECT * FROM `products`");
                    $select_products->execute();
                    if($select_products->rowCount() > 0) {
                        while($fetch_product = $select_products->fetch(PDO::FETCH_ASSOC)) {
                            ?>
                            <div class="single-menu-item" data-category="pizzas">
// menu form  
                                <form action="" method="post" onsubmit="onFormSubmit();">
                                    <input type="hidden" name="pid" value="<?= $fetch_product['id']; ?>">
                                    <input type="hidden" name="name" value="<?= $fetch_product['name']; ?>">
                                    <input type="hidden" name="last_name" value="<?= $fetch_product['last_name']; ?>">
                                    <input type="hidden" name="description" value="<?= $fetch_product['description']; ?>">
                                    <input type="hidden" name="details" value="<?= $fetch_product['details']; ?>">
                                    <input type="hidden" name="component" value="<?= $fetch_product['component']; ?>">
                                    <input type="hidden" name="price" value="<?= $fetch_product['price']; ?>">
                                    <input type="hidden" name="image" value="<?= $fetch_product['image_01']; ?>">
                                    <img src="uploaded_img/<?= $fetch_product['image_01']; ?>" alt="">
                                    <div class="single-menu-item-content">
                                        <h3>
                                            <?= $fetch_product['name']; ?>
                                        </h3>
                                        <h5>
                                            <?= $fetch_product['last_name']; ?>
                                        </h5>
                                        <p>
                                            <?= $fetch_product['description']; ?>
                                        </p>
                                        <p><b>
                                                <?= $fetch_product['details']; ?>
                                            </b>
                                        </p>
                                        <p>
                                            <?= $fetch_product['component']; ?>
                                        </p>
                                        <div class="b-f">
                                            <p class="price">
                                                <?= $fetch_product['price']; ?>le
                                            </p>
// submit button 
                                            <button class="fav-btn" type="submit" name="add_to_wishlist">
                                                <?php echo $button_text; ?>
                                                <svg class="heart-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
                                                    fill="#000000">
                                                    <path
                                                        d="M12 21.35l-1.45-1.32C5.4 14.25 2 11.45 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C15.09 3.81 16.76 3 18.5 3 21.58 3 24 5.42 24 8.5c0 2.95-3.4 5.75-8.55 11.54L12 21.35z" />
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            <?php
                        }
                    } else {
                        echo '<p class="empty">no products found!</p>';
                    }
                    ?>
                </div>
            </div>

and here is the wishlist_cart.php to handle the submtions

<?php
session_start();
include 'components/connect.php';

// Check if the form is submitted
if(isset($_POST['add_to_wishlist'])) {
    $pid = $_POST['pid'];
    $name = $_POST['name'];
    $last_name = $_POST['last_name'];
    $description = $_POST['description'];
    $details = $_POST['details'];
    $component = $_POST['component'];
    $price = $_POST['price'];
    $image = $_POST['image'];

    // Use session ID as a unique identifier
    $user_identifier = session_id();

    // Check if the item is already in the wishlist
    $check_wishlist_numbers = $conn->prepare("SELECT * FROM `wishlist` WHERE pid = ? AND user_identifier = ?");
    $check_wishlist_numbers->execute([$pid, $user_identifier]);

    if($check_wishlist_numbers->rowCount() > 0) {
        $message[] = 'Item is already in the wishlist!';
        $button_text = 'Added to Favorites';
    } else {
        // Insert the wishlist item into the database
        $insert_wishlist = $conn->prepare("INSERT INTO `wishlist` (user_identifier, pid, name, last_name, description, details, component, price, image) VALUES (?,?,?,?,?,?,?,?,?)");
        $insert_wishlist->execute([$user_identifier, $pid, $name, $last_name, $description, $details, $component, $price, $image]);
        $message[] = 'Item added to wishlist!';
        $button_text = 'Added to Favorites';
    }
} else {
    // Default button text
    $button_text = 'Add to Favorites';
}
?>

Do I have some sort of Shiny/Reactable/JavaScript conflict?

I have been working on a Shiny app and one part has been giving me trouble, and I was hoping to get a sanity check.
At one point, I have a Reactable, where I would like a custom onClick JS function to launch a modal. I have done this before successfully, but don’t have the code, so I am starting again from scratch.
Nothing I have done has worked – initially I thought it was a namespace issue (my app is modular/Golem), but the more things I have pared back in testing/trying to get this to work, the more I think I may have some sort of deeper issue.

I don’t think Reactables recognize any click actions for me?
I tried to go down to literally a bare-bones, single-file app with the copy and pasted Click Action demo directly from the Reactable docs, and I still get nothing. Can someone test the below and let me know if ANYTHING happens for you? (you get a logger line in your console, or a modal pops up, or a warning pops up, or even an error/crash! or anything? I just get… absolutely nothing).
I am wondering if I have some sort of internal conflict somewhere that is keeping my clicks from getting recognized?
Thank you!!

library(shiny)
library(reactable)
library(logger)

ui <- fluidPage(
  reactableOutput("reactableTest")
)

server <- function(input, output) {
  logger::log_shiny_input_changes(input)
  output$reactableTest <- renderReactable({
    data <- cbind(
      MASS::Cars93[1:5, c("Manufacturer", "Model", "Type", "Price")],
      details = NA
    )
    
    reactable(
      data,
      columns = list(
        # Render a "show details" button in the last column of the table.
        # This button won't do anything by itself, but will trigger the custom
        # click action on the column.
        details = colDef(
          name = "",
          sortable = FALSE,
          cell = function() htmltools::tags$button("Show details")
        )
      ),
      onClick = JS("function(rowInfo, column) {
    // Only handle click events on the 'details' column
    if (column.id !== 'details') {
      return
    }

    // Display an alert dialog with details for the row
    window.alert('Details for row ' + rowInfo.index + ':\n' + JSON.stringify(rowInfo.values, null, 2))

    // Send the click event to Shiny, which will be available in input$show_details
    // Note that the row index starts at 0 in JavaScript, so we add 1
    if (window.Shiny) {
      Shiny.setInputValue('show_details', { index: rowInfo.index + 1 }, { priority: 'event' })
    }
  }")
    )
  })
  
  observeEvent(input$show_details,{
    showModal(
      ui = modalDialog(
        title = "hey, it worked!",
        input$show_details
      )
      )
  })
}

shinyApp(ui, server)

Change reference ID of jQuery on(change) function

I would like to use a variable to change the reference Id in the script.

var groupId = "#groupOne input";
var groupValue = 1;
var radioValue;

function changeGroup() {
  groupId = "#groupTwo input";
  groupValue = 2;
}

$(groupId).change(function() {
  $('#x').text("Radio " + radioValue + " says " + groupId);
  $('#y').text(groupValue);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="radioGroup">
<div id="groupOne">
<input type="radio" name="1" id="1" value="1">
<label for 1="1">Radio 1</label>
<input type="radio" name="1" id="2" value="2">
<label for 1="2">Radio 2</label>
<input type="radio" name="1" id="3" value="3">
<label for 1="3">Radio 3</label>
</div>
<div id="groupTwo">
<input type="radio" name="2" id="4" value="4">
<label for 1="1">Radio 4</label>
<input type="radio" name="2" id="5" value="5">
<label for 1="5">Radio 5</label>
<input type="radio" name="2" id="6" value="6">
<label for 1="6">Radio 5</label>
</div>
</div>
<div>
<input type="button" onclick="changeGroup();" value="Change Group">
</div>
<div id="x"></div>
<div id="y"></div>

I have several groups of radio buttons in a div with id #groupOne.

This works as expected.

If #groupOne is changed to #groupTwo with another function the code still runs using the #groupOne Id.

How can I change the reference Id in the line of code to make this work on another div?

Use State not updating after being passed throw many children

Im passing a state showRemoveBtns down from my app component to my CardRemoveBtns component.
On updating the state it doesnt update the css.

My component tree (For better understanding):

App – Container – Content – ProductCard – CardRemoveBtns

|

AddRemoveBtns

CardRemoveBtns:

import './CardRemoveBtn.css';

export default function CardRemoveBtn(props) {

    function removeCard() {
        let updatedProducts = {...props.products}
        updatedProducts.users[props.activePerson].products = props.products.users[props.activePerson].products.filter(obj => obj.productName !== props.item.productName);
        props.setProducts(updatedProducts);
    }

    return(
        <div className={`cardRemoveBtn ${props.showRemoveBtns ? undefined : 'hidden'}`} onClick={removeCard}>
            x
        </div>
    )
}

ProductCard:

import { useRef, useEffect } from 'react';

import './ProductCard.css';

import CardRemoveBtn from './CardRemoveBtn';
 
export default function ProductCard(props) {

    const stars = useRef();

    useEffect(() => {
        for (let i = 0; i < props.product.priority; i++) { 
            stars.current.children[i].classList.add('checked');
        }
    })

    return(
        <div>
            <div className="card">
                <h1>{props.product.productName}</h1>
                <p className="price">R{props.product.price}</p>
                <p ref={stars} className="importance">
                    <span className="fa fa-star"></span>
                    <span className="fa fa-star"></span>
                    <span className="fa fa-star"></span>
                    <span className="fa fa-star"></span>
                    <span className="fa fa-star"></span>
                </p>
                <p><button onClick={() => window.open(props.product.productUrl)}>Visit site</button></p>
                <CardRemoveBtn showRemoveBtns={props.showRemoveBtns} products={props.products} setProducts={props.setProducts} activePerson={props.activePerson} item={props.product} />
            </div>
        </div>
    )
}

The State updates up until the Content component

I have tried making a

tag with the content of the state and it updates until Content Component

Upgrade JS decorator to the 2023-05 proposal?

I have a decorator to inject my common stylesheets into lit components written with the legacy 2018 proposal (as what was previously supported by lit). Upgrading to lit 3, they changed to the 2023-05 proposal and my decorator no longer works. How do I update my decorator to the 2023-05 proposal?

My understanding is fields no longer have initializers, so I’m not sure how to do this now:

Decorator

const injectTheme = (...styles) => (target) => {
  const { initializer } = target;

  // Inject tailwind
  let newStyles = [tailwind];

  // Add any initial styles into the new style array
  if (initializer) {
    const initStyles = initializer.call(this);
    if (Array.isArray(initStyles)) {
      newStyles.push(...initStyles);
    } else {
      newStyles.push(initStyles);
    }
  }

  // Add passed in styles last
  newStyles.push(...styles);

  // Remove any invalid styles
  newStyles = newStyles.filter((style) => !!style);

  // Ensure that they are valid style sheets
  newStyles = newStyles.map(assertCSS);

  // Override initializer to return new styles array
  target.initializer = function () {
    return newStyles;
  };
};

Example Usage

import styles from './styles.css';

@customElement('my-element')
class MyElement extends LitElement {
  @injectTheme(styles) static styles;
}

Preferred Syntax

Is it possible to make this a class decorator as I think I’d prefer that. Only issue I see is that class decorators are called after the static elements are assigned:

Class decorator initializers are run after the class has been fully
defined, and after class static fields have been assigned.

@injectTheme(style)
@customElement('my-element')
class MyElement extends LitElement {

}

https://github.com/tc39/proposal-decorators

What is the scope of a variable declared with ‘var’ inside of a function in JavaScript [duplicate]

I saw another post with the same question and it seemed to have differing explanations. Online resources also seem to have conflicting explanations, unless I am misunderstanding something.

MDN says:

“The scope of a variable declared with var is one of the following curly-brace-enclosed syntaxes that most closely contains the var statement:

Function body

Static initialization block

Or if none of the above applies:

The current module, for code running in module mode

The global scope, for code running in script mode.”

My interpretation of this is that the answer to my question would be local scope – local to the function.

w3schools on the other hand says:

“Variables declared with the var keyword can NOT have block scope.

Variables declared inside a { } block can be accessed from outside the block.”

If my understanding that function scope is an example of block scope, then this tells me that variables declared inside of a function (which is a block) cannot have block scope – and thus has global scope.

freeCodeCamp says:

“Variables which are declared without the let or const keywords are automatically created in the global scope”

Which also suggests to me that variables declared inside of a function with the var keyword have global scope.

So I am confused as to what the answer is, does a variable declared with the var keyword inside of a function (in the context of JavaScript) have global scope or local scope (local to the function)?

I am sure there is something I am misunderstanding – perhaps a misuse of terminology. Thank you in advance.

node.js / javascript / SQL with async/await – not behaving synchronously

I am trying to call function that makes SQL call and returns the data to the calling function
I am trying unsuccessfully to use async/await (promises) syntax in node.js/javascript
My function is still behaving asynchronously.

Perhaps not quite understanding how this is supposed to work.
See notes in code

const {dbconn, dbstmt} = require('idb-pconnector');

async function get_data(){

        const {dbconn, dbstmt} = require('idb-connector');
        const sql_stsmt = 'SELECT * FROM QIWS.QCUSTCDT';
        const conn1 = new dbconn();
        conn1.conn('*LOCAL');
        const stmt = new dbstmt(conn1);

        try {
            await stmt.exec(sql_stsmt, (x) => {
            stmt.close();
            conn1.disconn();
            conn1.close();            
            // getting expected data here..
            console.log("1..")     
            console.log("%s", JSON.stringify(x));                
            return x;
            });
        }
        catch (error) {
            return console.error(error);            
            }
    }

async function main() {
    try{
        const result = await get_data()
        console.log("2..")     
        // still coming out undefined here...
        console.log("%s", JSON.stringify(result));                
        return result;
    }
    catch(error){
        return console.error(error);            
    }
}

let data = main();
console.log("3..")     
// coming out empty {} here.
console.log("%s", JSON.stringify(data));                

Uncaught (in promise) TypeError: window.indexedDB.databases is not a function

First time attempting this sort of function and I’ve tried numerous approaches, but can’t figure out what I’m doing incorrectly. I always get an uncaught error… why?

Specifically, I get the following error:

Uncaught (in promise) TypeError: window.indexedDB.databases is not a function

function dbReady(dbName, callback) {
    if(typeof window !== "undefined") {
        (window.indexedDB.databases()).then(dbs => function(dbs) {
            const dbExists = dbs.map(db => db.name).includes(dbName);
            if(dbExists && typeof callback === 'function') { callback(dbExists); return dbExists;}
            else {throw new Error('databases() Failed:');}
        }).catch((e) => {
            console.error(e);
        });
    } else if(typeof callback === 'function') { callback(true);}
};

thank you in advance! …first time posting on here… if that says something about my level of frustration 🙂

I tried various approaches using .then() vs try / catch vs. await… I really don’t know what I’m doing so just trying what I’ve come across on this website with others trying to solve for similar situations.

Need to learn complete JavaScript first to understand react js? [closed]

As a UI-UX designer with over a decade of experience and some knowledge of HTML5/CSS3 and the Bootstrap framework, I am now interested in learning the React JS framework.

I am unsure whether to start from scratch and learn JavaScript first before diving into React JS or learn both simultaneously. Which path would be better in this competitive world?

I have come across conflicting opinions on various video platforms.

Some say that learning JavaScript is a must before learning React JS, while others suggest that learning React JS itself is enough since it covers JavaScript as well.

Can someone please guide me in the right direction?

vue3 – computed ref in table

on the vue3 page below I have integrated a player that shows a “play” icon when the player is stopped, and a “pause” icon when it’s playing.

What I am now trying to do is to let the player repeat n-times by including it in a table.

The difficulty I have is that I currently use the “ref” of the player (“audioPlayer”) below as input to the “compute”, and since when I repeat the player n-times I can’t hard-code the player’s ref, I need to find a way how the “isPlaying” is evaluated dynamically for the audioPlayer in the respective Row.

I tried to use methods, higher-order functions (as explained here) but have not been able to figure it out.

Any pointers would be appreciated.

Thank you

P.s. The below example works; What is missing is sticking he player in the repeating , since there I have not been able to figure out how to compute the isPlaying correctly depending on which row I am in

<template>
  <div v-for="index in 3" :key="index"> 
    {{ index }}. player should go here <p></p> <!-- <<<<<<<<< The player below should be repeated here -->
    ----------------------------------
  </div>

  <div v-if="!isPlaying" class="audio__play-start"  @click.stop="this.$refs.audioPlayer.play"><q-icon name="play_circle"></q-icon></div>
  <div v-else class="audio__play-pause" @click.stop="this.$refs.audioPlayer.pause"><q-icon name="pause_circle"></q-icon></div>
  
  <div>
    <audio-player
      ref="audioPlayer"
      :audio-list="['./api/soundfiles?path=/tmp&filename=rock.mp3']"
      theme-color="black"
      :show-prev-button="false"
      :show-next-button="false"
      :show-play-button="false"
      :show-volume-button="false"
      :show-playback-rate="false"
    />
  </div>
</template>

<script lang="ts">
import { ref, computed } from 'vue';

export default {
  
  setup () {
    const audioPlayer =  ref(Object)
    const isPlaying = computed(() => {  
      return audioPlayer.value.isPlaying
    })

    return {
      audioPlayer,
      isPlaying
    }
  },

}
</script>

SVG.js how to include the filter module plugin and use it in javascript

I have gone to the filter plugin page for svg.js and as usual did not get a clear explanation of how to include it in an html page. But instead get very vague and incomplete instructions. The link is : svg filter plugin

Below is my attempt at including the plugin and making a java script reference to it …

<html>
    <head>
        <title>SVG.js</title>
        <style>
            html, body, #drawing{
                width:100%;
                height:100%;
            }
        </style>
        <script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>
        <script src="svg.filter.js"></script>
    </head>
    <body onload="onload();">
        <div id="drawing"></div>
        <script>
            function onload() {
                var draw = SVG().addTo('#drawing').size(800, 800);
                var rect = draw.rect(100, 100).attr({fill: '#f06', x:50, y:50});
                rect.filter(function(add) {
                  add.gaussianBlur('15')
                });       
                var image = draw.image('bear.jpg').size(300, 300);
                for (var i in image) {
                    console.log(i);
                }
                image.filterWith(function (add) {
                    add.gaussianBlur(30)
                });
            }
        </script>
    </body>
</html>

I get back an error in the browser console stating …

Uncaught SyntaxError: Cannot use import statement outside a module (at svg.filter.js:1:1)
svg-filters.html:20 Uncaught TypeError: rect.filter is not a function
    at onload (svg-filters.html:20:22)
    at onload (svg-filters.html:14:30)

The instructions merely state …

Npm
npm i @svgdotjs/svg.filter.js
Yarn
yarn add @svgdotjs/svg.filter.js

Include this plugin after including the svg.js library in your html document.

My question has 2 parts :

  1. Where does Npm and Yarn fit into the picture to get the code running and how do i make the code work ?
  2. What is the cdn link for svg.filter.js like ‘https://cdn.jsdelivr.net’ ?

Thanks in advance for anyone willing to help out.

MongoDB returning undefined object

New to express and mongo but I’ve been trying to pull from my a Local MongoDB database hosted on my own device using express.js .find() function, so far ive had no luck. I get ‘[]’ back in the console, it may be an empty string or an undefined object. Ive tried many things
-changing the schema or removing it all together when defining my model

  • i have confirmed that the data does exist in my database and i can see it on compass and with mongosh
  • i have tried checking my firewall and network setting to make sure that windows is not blocking my server from communicating with my database
    -I have tried sending the information as a json object instead and i still get the same thing
    here is my code:
const express = require('express'); 
const mongoose = require('mongoose');
const app = express(); 
const PORT = process.env.PORT || 3000;
const uri = 'mongodb://127.0.0.1:27017/Test'
mongoose.connect(uri);
const db = mongoose.connection;
db.on('connected', ()=> {
    console.log('Success');
});
db.on('error', (err)=> {
    console.log('error', err);
});
mongoose.connection.on('disconnected', ()=> {
    console.log('disconnected');
});

const Model = mongoose.model('model', new mongoose.Schema({}));
app.use(express.json());


db.Model.find()
    .lean()
    .exec()
    .then(data => {
        if (data){
            console.log('data:', data);
        }  else{
            console.log('no data');
        }
  })
app.get('/', async(req, res) => {
        try {
        const posts = await Model.find({});
        res.send(posts)
    } catch (error) {//error block
        res.status(500).json({ error: error.message });
    } 
});

app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Excel Web AddIn Javascript API formula corruption until we manually reload the addin

We are having issues with the new Excel Web AddIn (Javascript API). The formulas are getting corrupt on initial load of the file from One Drive. If we go in to Addins and Refresh the Addin, it works.

Proper formula name: GET_CUSTOM_DATA()

Corrupted name:

=xxxx_xldudf_GET_CUSTOM_DATA()

Formulas auto correct to the proper name when the addin is reloaded. This can be either through readding the addin through the ‘Insert’ Tab and ‘My Addins’. Or by clearing the excel cache and letting the addin reload itself on Excel restart.