I am getting refresh after executing submit button in login form

I make a simple login page using html and css and javascripts.
But when i submit and in case of some javascript lines execution after few seconds the page refresh automatically.when i submit form it shows desiered output but is few seconds webpage refresh.
HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>intern.local</title>
    <link rel="stylesheet"><link rel="stylesheet" href="./index.css">
    <script src="./index.js"></script>
</head>
<body>
<div class="outer"> 
    <div class="inner one" 
        id="box_one">
        <h1 class="main">
            Welcome to intern.local
        </h1>
        <h3 id='login_1'>
            Enter details and login to continue.
        </h3>
    </div>
    <div class="inner two" 
        id="box_two">
        <div class="head">
            <h1> Welcome</h1>
            <h2>Please Login</h2>
            <div class="error">
                    Please Enter valid Password.
            </div>
            <div id="login" 
                class="login">
                
                <form class="login_form" onsubmit="validate()">
                    
                    <input type="text"
                            pattern="^w+([.-]?w+)*@docquity.com"
                            id="uname" 
                            class="inp uname" 
                            name="uname"
                            placeholder="Username" required><br>
                    <input type="password" 
                            minlength="6"
                            id="pass" 
                            class="inp pwd" 
                            name="pass"
                            placeholder="Password" required>
                    <small id="pass_error"></small>
                    <input type="submit" 
                            id="smt" 
                            value="Submit"
                            class="btn sbmt">
                </form>
                
            </div>
        </div>
    </div>
</div>    
</body>
</html>

css code

body {
    margin:0px;
    height:100%;
    border: none;
    padding:0px;
  }

.inner{
    float:left;
    width: 50%;
    height: 100vh;

}
.one {
    background-color:cornsilk;
}
.two{
    /*background: rgb(63,94,251);*/
    background: radial-gradient(circle, rgb(103, 126, 238) 0%, rgb(185, 74, 97) 150%);
    padding: 0%;
    border: 0%;
    margin: 0%;
    color: cornsilk;
}
.head{
    height: auto;
    padding-top: 15%;
}
.head h1 {
    text-align: center;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    font-size: 40px;
}
.head h2{
    text-align: center;

}
form {
    margin: 0 auto;
}
.login {
    text-align: center;
}
.inp {
    border: none;
    background: none;
    box-shadow: 0px 2px 0px 0px white;
    width: 50%;
    color:blanchedalmond;
    font-size: 25px;
    outline: none;
    margin-left: 20%;
    margin-right: 20%;
    margin-top: 5%;
    padding-left: 2%;
}
.inp:focus:invalid{
    box-shadow: 0px 2px 0px 0px red;
}
small {
    color: red;
    font-weight: bold;
}
.pwd {
    margin-bottom: 10%;
}
.uname::placeholder, .pwd::placeholder{
    color: blanchedalmond;
}
.btn {
    align-items: center;
    background-color: #fff;
    border-radius: 24px;
    border-style: none;
    box-shadow: rgba(0, 0, 0, .2) 0 3px 5px -1px,rgba(0, 0, 0, .14) 0 6px 10px 0,rgba(0, 0, 0, .12) 0 1px 18px 0;
    box-sizing: border-box;
    color: #000102;
    display: inline-flex;   
    height: 48px;
    justify-content: center;
    padding: 2px 24px;   
    width: 30%;
    font-size: 25px;
    
    
}
.sbmt:hover{
    background-color: darkslategray;
    color: floralwhite;
}

.main {
    margin-top: 20%;
    text-align: center;
    font-size: 60px;
    background: -webkit-linear-gradient(rgb(171, 10, 185), rgb(209, 8, 42));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.one h3 {
    text-align: center;
    color:darkslategray;
}

.error_message{
    background-color: red;
    margin-left: 25%;
    margin-right: 25%;
    text-align: center;
}

.error {
    display: none;
}



javascript code

function mail_velidate(mail){
  var mail_pattern = /^w+([.-]?w+)*@docquity.com/;
  if(mail.match(mail_pattern))
  {
    return true;
  }
  else{
    return false;
  }
}

function password_check(pass){
  var pass_regex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{7,15}$/;
  if (pass.match(pass_regex)){
    return true;
  }
  else{
    return false;
  }
}
const mail = document.getElementById("uname");

document.addEventListener("DOMContentLoaded", function() {
    var elements = document.getElementsByClassName("uname");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Give valid docquity mail id");
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})

function validate(){
  var user = document.getElementById("uname").value;
  var pass = document.getElementById("pass").value;

  if(password_check(pass)){
      document.getElementById('login').innerHTML = "<h1>Logged In</h1>";
      document.getElementById('login_1').innerHTML = '<h3>Logged In successfully</h3>';
      document.getElementById('box_two').style.display = 'none';
      document.getElementById('box_one').style.width = '100%';
  }
  else{
    document.getElementsByClassName("error")[0].className = "error_message";
  }
}

the line of code document.getElementsByClassName("error")[0].className = "error_message"; giving me problem.

List items with inputs – how to add list object to an array when input has value?

I have created a list of objects and each list item has input within:

{flowers_data?.map((flower) => {
   return (
      <>
         <div className={classes.Nested_Flower_Container} key={flower.id}>
            <div className={classes.Nested_Flower_Name}>
               {flower.name}
            </div>
         <div className={classes.Nested_Flower_Input} style={{ marginRight: '0.2em' }}>
            <TextField
              id="Amount"
              label="Amount"
              variant="outlined"
              size="small"
              type="number"
              onChange={(e) => {
                 setAmount(e.target.value);
                 handleAddList(e.target.value, flower);
              }}
              className={classes_2.root}
            />
         </div>
      </div>
  </>)
})}

How can I add an object that has a value in input to an array? I tried to do this using a function that I created, but each time I change one element’s target.value and move on to the next item to change its input value, there is only one element in the array with the latest target.value. And after modifying the inputs, when I try to output the values outside that function with e.g. a button, the add_flowers_tab array is empty.

handleAddList function:

let temp_flower: Flower;
let add_flowers_tab: Flower[] = [];

    const handleAddList = (targetValue: string, flower: Flower) => {

        temp_flower = {
            "id": flower.id,
            "name": flower.name,
            "price": flower.price,
            "amount": Number(targetValue),
            "creation_date": flower.creation_date
        }

        if (targetValue === '') {
            /* Delete flower when input is empty */
            add_flowers_tab.forEach(tabFlower => {
                if (tabFlower.id === temp_flower.id) {
                    const indexOfDelete = add_flowers_tab.indexOf(tabFlower);
                    add_flowers_tab.splice(indexOfDelete, 1);
                }
            })
        }
        if (targetValue !== '') {
            /* Add flower to tab when input has value */
            if (add_flowers_tab.length > 0) {
                /* When input changes, delete flower with old input value and add the new one */
                add_flowers_tab.forEach(tabFlower => {
                    if (tabFlower.id === temp_flower.id) {
                        const indexOfDelete = add_flowers_tab.indexOf(tabFlower);
                        add_flowers_tab.splice(indexOfDelete, 1);
                        add_flowers_tab.push(temp_flower);
                    }
                })
            }
            else {
                /* Add new flower as a first element in the array */
                add_flowers_tab.push(temp_flower);
            }

            /* 
               Displays an array with only the most recently added temp_flower, even though 
               several inputs in list have values
            */

            console.log(add_flowers_tab);
        }
    }

throw new TypeError(‘Router.use() requires a middleware function but got a + gettype(fn)). (other problem)

hi, i’m writing a application under NodeJS but got the following error:

throw new TypeError(‘Router.use() requires a middleware function but got a ‘ + gettype(fn))
^

TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:Usersdecopiaporestserver1221node_modulesexpresslibrouterindex.js:458:13)
at Function. (C:Usersdecopiaporestserver1221node_modulesexpresslibapplication.js:220:21)
at Array.forEach ()
at Function.use (C:Usersdecopiaporestserver1221node_modulesexpresslibapplication.js:217:7)
at Server.routes (C:Usersdecopiaporestserver1221modelsserver.js:58:14)
at new Server (C:Usersdecopiaporestserver1221modelsserver.js:19:14)
at Object. (C:Usersdecopiaporestserver1221app.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
[nodemon] app crashed – waiting for file changes before starting…

The Code is:

const {Router} = require(‘express’);

const { check } = require(‘express-validator’);

const { login} = require(‘../controllers/auth’);

const { validatefields } = require(‘../middlewares/validate-fields’);

const router = Router();

router.post(‘/login’, [

check(’email’, ‘Email is mandatory’).isEmail(),

check(‘password’, ‘The Password is mandatory’).not().isEmpty(),

validatefields

],

login);

module.exports = {
router
}

….

note

If i change “module.exports = { router }” for “module.exports = router” the problem disappears, but what if i want to export a constant or other function?

example:

const {Router} = require(‘express’);

const { check } = require(‘express-validator’);

const { login} = require(‘../controllers/auth’);

const { validatefields } = require(‘../middlewares/validate-fields’);

const myvar = ‘12321@as’;

const router = Router();

router.post(‘/login’, [

check(’email’, ‘Email is mandatory’).isEmail(),

check(‘password’, ‘The Password is mandatory’).not().isEmpty(),

validatefields

],

login);

module.exports = {
router,
myvar
}

the error appears again…

throw new TypeError(‘Router.use() requires a middleware function but got a ‘ + gettype(fn))
^

TypeError: Router.use() requires a middleware function but got a Object
at Function.use

How i can solve this problem. Any Ideas?

Node Version: v16.11.1 –
Express Version : 4.17.1

Stop Form From Being Submitted Until Verified

I have a form structured as so.

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/">
   <div class="form-group">
      <label for="id_email_address" class="d-none">Email Address</label>
      <input type="email" id="id_email_address" class="form-control border-0 rounded-0" name="email_address" value="" placeholder="Email Address">
      <input type="hidden" name="mailpiece_slug" value="{{ page.settings.email_newsletter_slug }}" />
      <input type="hidden" name="event_slug" value="subscribe" />
   </div>
</form>

I also have a script at the bottom of the file. The point of the script will be to verify a recaptcha before submitting the form. Here is my script.

<script>
    document.getElementById('email_subscription_form').addEventListener('submit', verifyRecaptcha);
    
    function verifyRecaptcha(e) {
        e.preventDefault()
        return false
    }
</script>

I was thinking, based on some research, that the function returning false would stop the form from submitting. However, the form still submits and hits the endpoint.

I have also tried this:

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsubmit="return verifyRecaptcha()">

and

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsbubmit="return false">

but the form still submits.

What can I do to stop the form from submitting until verified? This is a Django project, so the template is a Django template.

How access JS function using Import Maps in Ruby On Rails 7?

I’m newbie to JS modules and Import Map, now I’m using Ruby on Rails 7 and I couldn’t find a way to get this working:

Js Module (proposals.js):

function openProposalMirror() ...

application.js

import * as Proposal from "./proposals.js"

On the view:

onclick="Proposal.openProposalMirror()"

error: Uncaught ReferenceError: Proposal is not defined

How could I accesse openProposalMirror() function on the view?

Print CV in JavaScript

how can I print my resume from my PC using JavaScript?
I’ve added my resume in the HTML element, like this:
<a href="images/CVAndrea.docx" class="btn hero-btn">hire me</a>

However, I don’t know what I can do to print the resume when clicking on the link.

Someone can help me, please?

Thanks!

Files don’t import in vscode

I just started using vscode and my files in the same directory wont import to files in the same directory. For example when I link to css or javascript files from an html file, they aren’t read and the websits opens without the functions in the javascript file operating and same goes for the css file. When I imported flask forms from a file to my main flask application page in python, it wouldn’t work and I would get the error, ‘no module named ‘flaskform’.

What settings configurations am I missing for vscode?

useRef current and click event target are not equal even though they should be [duplicate]

I have a div element that I want to call a function from when a click event fires on it. The div contains an input field that I don’t want to trigger the function, so I’m using useRef to target only the div element itself and not the contents. I’m creating the reference with the hook, giving the div a ref attribute pointing to that reference, and then passing it an onClick event that first checks if ref.current is equal to the event target. This method has worked for me in the past when building features such as modals, but for some reason this time the value of ref.current and the value of the event target are not evaluating as equal, and so the function never fires off. Here’s the code:

const VideoEntryTile: React.FC = () => {
  const [isExpanded, setIsExpanded] = useState<boolean>(false);
  const containerRef = useRef<HTMLDivElement | null>(null)

  const handleExpand = (e: any):void => {
    console.log(containerRef === e.target) // This evaluates to false
    if (containerRef.current === e.target) {
      setIsExpanded(true)
    }
  }

  return (
    <div
      className={styles.VideoEntryTile__Container}
      onClick={handleExpand}
      ref={containerRef} {/* The reference is set here */}
    >
      <div className={styles.VideoEntryTile__Top}>
        <div className={styles.VideoEntryTile__LeftActions}>
          <div className={styles.VideoEntryTile__LeftActions__VideoNameInput}>
            <TextField
              disabled={false}
              inputSize="large"
              value="Video 1"
            />
          </div>
          <div className={styles.VideoEntryTile__LeftActions__GuestsContainer}>
            <p>Guests</p>
            <input />
          </div>
          <button type="button">-</button>
          <button type="button">+</button>
        </div>
        <div className={styles.VideoEntryTile__RightActions}>
          <p>20</p>
          <p>Credits</p>
        </div>
      </div>
      { isExpanded ?
        (
          <div className={styles.VideoEntryTile__Bottom}>
            <p>Test</p>
            <p>Test</p>
            <p>Test</p>
            <p>Test</p>
            <p>Test</p>
          </div>
        )
        : null }
    </div>
  );
};

Any idea why this isn’t working? This solution has worked for me in the past so I’m not sure why it isn’t now.

E: This thread should not have been closed – the provided “answer” has nothing to do with my question.

Lealet – Cluster geojson Layer doesn’t work with marker filtering

I’m doing a leaflet map with some GEOjson data.
I try to add the cluster function to my js file. As I added some filter and styling features according to properties, I’m unable to find the right way to code the cluster fonction.

Here is the Geosjson layer and the filter verificator:

const geojsonLayer = L.geoJSON(null,{
filter: (feature) => {
const isYearChecked = checkboxStates.years.includes(feature.properties.year)
const isEventTypeChecked = checkboxStates.eventTypes.includes(feature.properties.eventType)
return isYearChecked && isEventTypeChecked }, //only true if both are true

with the syling function:

              var year = feature.properties.year;
              if (year <= -150) {
                  return {
                      color: "black"
                  };

I add then the popup:

layer.bindPopup(popupText, {
       closeButton: true,
       offset: L.point(0, -10)
          });
     layer.on('click', function() {
       layer.openPopup();
     });
   },
}).addTo(map);

I try to add this piece of code to display the cluster but I don’t know where to place it in my code in order to work (https://github.com/Leaflet/Leaflet.markercluster):

var markers = L.markerClusterGroup();
markers.addLayer(L.marker(getRandomLatLng(map)));
... Add more layers ...
map.addLayer(markers);

My whole code is available here: https://github.com/jandre3/pince-crochet

Thank you for your advices. Sorry if the question is very easy, I’m new in JS.

node.js Cannot read properties of undefined (reading

I m getting this TypeError: Cannot read properties of undefined (reading ‘$variable’)

I have written a snippet of code to update the prices of coins in my database, but it gives this error after working for a certain period of time.

Err:

                                   ^
TypeError: Cannot read properties of undefined (reading 'MIRUSDT')
    at c:xamppxshtdocs1patron.js:58:36
    at Request._callback (c:xamppxshtdocs1node_modulesnode-binance-apinode-binance-api.js:3263:37)

My code:

const priceup = async () => {
 
  connection.query("SELECT * FROM pricetracker WHERE price_coinstatus='0'", function (err, rows, fields) {
    if (err){priceup()};
    rows.forEach(function(row) {
        let symbol = row.price_coin;
        let id = row.price_coinid;
        let entryprice = row.price_coinentryprice;
         
                        var day=dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true);
 
        const tt = binance.prices(symbol, (error, ticker) => {
            if (error){priceup()};
            var hede = ("price", ticker);
            var hededegisken = hede[symbol];
            if(typeof hededegisken === 'undefined' || hededegisken === null) {
               priceup()
            }
            var percent = (hededegisken - entryprice) * 100 / hede[symbol];
            
            var percent = Number(percent).toFixed(4)
             
            if (percent > 2){
                var percent = '<span class="bg-success p-1">+<i class="mdi mdi-arrow-up-bold"></i>'+percent+'%</span>';
            }else if (percent >= 0){
                var percent = '<span class="bg-warning p-1">+<i class="mdi mdi-arrow-up-bold"></i>'+percent+'%</span>';
            }else if (percent >= -2){
                var percent = '<span class="bg-danger p-1"><i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }else if (percent >= -4){
                var percent = '<span class="bg-danger p-1"><img src="../images/patience.png" height="18" title="Warning!"> <i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }else if (percent >= -6){
                var percent = '<span class="bg-danger p-1"><img src="../images/patience.png" height="18" title="Warning!"><i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }else if (percent >= -8){
                var percent = '<span class="bg-danger p-1"><img src="../images/patience.png" height="18" title="Warning!"><i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }else if (percent >= -10){
                var percent = '<span class="bg-danger p-1"><img src="../images/patience.png" height="18" title="Warning!"><i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }else{
                var percent = '<span class="bg-danger p-1"><img src="../images/patience.png" height="18" title="Warning!"><i class="mdi mdi-arrow-down-bold"></i>'+percent+'%</span>';
            }
 
             
            // console.log(percent);
                connection.connect(function(err){
                  
                    var sql = "UPDATE pricetracker SET price_coin='"+symbol+"',price_lastprice='"+hededegisken+"',price_percent='"+percent+"',price_uptime='"+day+"' WHERE price_coinid='"+id+"'";
                      
                        connection.query(sql,function(err,result){
                        console.log(symbol+' Update! '+day)
                        
 

                        });
                         
                });
            if (err){
                priceup()
            }
        });
    });
  });
};

How can I solve this?

What’s the point of _curry1() in ramda.js?

I am reading right now the source code of rambda.js and don’t understand the point of _curry1().

function _curry1(fn) {
  return function f1(a) {
    if (arguments.length === 0 || _isPlaceholder(a)) {
      return f1;
    } else {
      return fn.apply(this, arguments);
    }
  };
}

Functions that are curried with this function can be called without arguments.

const inc = (n) => n + 1
const curriedInc = _curry1(inc)

// now it can be called like this
curriedInc(1)   // => 2
curriedInc()(1) // => 2

// but it works only with no arguments provided
const add = (a, b) => a + b
const curriedAdd = _curry1(add)

curriedAdd(1)     // => NaN
curriedAdd(1)(1)  // => TypeError: curriedAdd(...) is not a function
curriedAdd()      // => function f1(a)

Question:
It seems to me that you can’t chain arguments with this function at all. What are use cases for this function? How different is curriedInc()(1) from inc(1)?

Return array that is not empty

I have two array like this

const array1 = ['1','2','3'];
const array2 = [];

But it can be that array1 is emptyand second array2 have members, what i need is that i want to create getter to return me array that is not empty, something like this

 get notEmptyArray(): string[] {
    const array1 = ['1','2','3'];
    const array2 = [];
    return array1 or array2;
  }

I know i can do it like

if (typeof array !== 'undefined' && array.length === 0) {
    // the array is defined and has no elements
}
if (array && !array.length) {
    // array is defined but has no element
}

But is there some simple inliner for that?

Smooth max-height when removing

I have got a element I open using a transition so it’s smooth, I then remove the set height when it is done so that the content can define the height.

However when closing the transition doesn’t work, it’s just an abrupt close.

Vue.component('test', {
  template: `<div>
  <a href="javascript:void(0)" @click="isActive = !isActive">Expand</a>
  <div ref="content" class="content"></div>
  </div>`,
  data() {
    return {
      isActive: false
    } 
  },
  mounted() {
   const _this = this;
    this.$refs.content.addEventListener('transitionend', function() {
      console.log('end');
      _this.$refs.content.classList.add('show');
      _this.$refs.content.style.maxHeight = null;
    })
  },
  watch: {
    isActive() {
      if (!this.isActive) {
        this.$refs.content.style.maxHeight = `${300}px`;
        return;
      }
      this.$refs.content.style.maxHeight = null;
      this.$refs.content.classList.remove('show');
    }
  }
});

new Vue({}).$mount('#app');
.content {
  background: red;
  height: 500px;
  display: block;
  transition: max-height .3s ease;
  max-height: 0;
}
.content.show {
  max-height: unset;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <test></test>
</div>

Nuxt Dynamic routes returns 404 after static generation

guys. I have a shop page with two params: page and sort. like below:

example.com/shop/
example.com/shop/page/2/
example.com/shop/sort/newest/
example.com/shop/sort/oldest/page/2/

this is my route configs:

router: {
    extendRoutes(routes, resolve) {
      routes.push(
        {
          path: '/shop/sort/:sort/page/:page(\d+)',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-sort-page',
        },
        {
          path: '/shop/sort/:sort',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-sort',
        },
        {
          path: '/shop/page/:page(\d+)',
          component: resolve(__dirname, 'pages/shop/index.vue'),
          name: 'shop-page',
        },
      )
    }
},

Now, after i generate my website, Nuxt doesn’t generate sort pages. when i go to /sort/ or /sort/oldest/page/2/ it returns 404.

what do I need to do?
if I need to generate all these pages by myself, then what are these routes.push() used for?

I also want to add “name” and “filter” params. you see generating a dynamic route for all these parameters is impossible. what can I do?
thanks.