Validation continues when input value is deleted

There are validations for mandatory input fields. Validation works when these fields are unfilled or filled incorrectly. After filling the field I delete it but the validation still works and an error message pops up. I don’t want validation to run when input value is deleted.

js

const [nameValidationState, setNameValidationState] = useState({
 error: false,
 helperText: '',
});

const nameOnChange = (event) => {
 if (nameValidator(event.target.value)) {
  setNameValidationState({ error: false, helperText: '' });
  setPaymentInfo({
   ...paymentInfo,
   firstName: event.target.value,
  });
 } else {
   setNameValidationState({ error: true, helperText: 'Please enter your name.' });
   setPaymentInfo({
    ...paymentInfo,
    firstName: null,
   });
 }
};

const handleInputChange = (event) => {
 const { name, value } = event.target;
 setPaymentInfo({ ...paymentInfo, [name]: value });
};

const handleFirstNameChange = (event) => {
 nameOnChange(event);
 handleInputChange(event);
};

html

<AS.TextField
 id="outlined-basic"
 label={t('general.name')}
 variant="outlined"
 sx={{ width: '100%', maxWidth: '500px', margin: 'auto' }}
 InputLabelProps={{
  shrink: true,
 }}
 placeholder=""
 onChange={handleFirstNameChange}
 error={nameValidationState.error}
 helperText={nameValidationState.helperText}
 name="firstName"
 value={paymentInfo.firstName}
/>
<AS.TextField

validator.js

export const nameValidator = (name) => {
  const nameRegex = /^[a-zA-ZwığüşöçĞÜŞÖÇİ]+$/;
  return nameRegex.test(name);
};

White line in div hides text (custom component)

I am currently working in ReactJS together with some SCSS / CSS stylings.

However, I made a component, that lists number codecs on hover.
In normal state it’s a div, that indicates a small or big damage size.
When you hover on it, it opens the listed mentioned above.

For some reason, I always have this white line, ditching my number coded so I can’t be read. What did I miss? My code is below.

DAMAGE_SIZE_STATUSES = {
GREEN: ‘green’,
YELLOW: ‘yellow’,
RED: ‘red’,
};

‘index.js’

...

  const criticality =
    // eslint-disable-next-line no-nested-ternary
    critical && criticalConditions.some((condition) => condition.fulfilled)
      ? DAMAGE_SIZE_STATUSES.RED
      : critical
      ? DAMAGE_SIZE_STATUSES.YELLOW
      : DAMAGE_SIZE_STATUSES.GREEN;

  const criticalityTextKey = getIndicatorStatusTextKey(criticality);
  const criticalityIcon = getIndicatorStatusIcon(criticality);

return
<div className={classNames('DamageSizeIndicator', criticality)}>
      <div className="content">
        <div className="title">
          <div className="criticality">
            {criticalityIcon && <Icon type={criticalityIcon} theme="filled" />}
            {t(criticalityTextKey)}
          </div>
          <div className="condition" />
        </div>
        {critical ? (
          <ul className="critical-icds">
            {criticalConditions.map((icd) => (
              <li
                key={`critical-icd_${icd.code}`}
                className={classNames({
                  'icd-fulfilled': icd.fulfilled,
                  'icd-unfulfilled': !icd.fulfilled,
                })}
              >
                <div className="icd-description">
                  <span>ICD {icd.code}</span>
                  <Tooltip title={icd.description}>{icd.description}</Tooltip>
                </div>
                <div className="icd-condition">
                  <span>
                    <Icon
                      type={
                        icd.fulfilled ? 'check-circle' : 'exclamation-circle'
                      }
                    />
                    {t(getConditionFulfilledTextKey(icd.fulfilled))}
                  </span>
                  {icd.condition}
                </div>
              </li>
            ))}
          </ul>
        ) : null}


styling.scss

@import 'src/app/variables.scss';

.DamageSizeIndicator {
  display: flex;
  flex-direction: column;
  height: 72px;
  justify-content: flex-start;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: 450;
  white-space: nowrap;
  margin-left: 25px;

  position: relative;
  z-index: 2;

  .content {
    display: flex;
    flex-direction: column;
    box-shadow: $overlay-shadow;
    border-radius: $overlay-radius;
    position: absolute;

    .title,
    .critical-icds {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      flex: 1;

      border-radius: $overlay-radius;
      padding: 10px;

      transition: 0.2s linear all;

      i {
        margin-right: 0.5em;
      }
    }

    .title {
      background: $colorSubtleWhite;
      font-size: $titleFontSize;

      .condition {
        display: none;
        white-space: nowrap;

        padding-left: 0.5em;
      }
    }

    .critical-icds {
      background: $colorSubtleGray;
      font-size: $subTitleFontSize;

      display: none;
      list-style: none;
      margin: 0;

      flex-direction: column;

      li {
        width: 100%;
        margin: 0;

        display: flex;
        flex-direction: column;

        span {
          color: $colorGray;
          white-space: nowrap;
          padding-right: 0.5em;
        }

        .icd-description,
        .icd-condition {
          color: $colorLightBlack;
          position: relative;

          max-width: 350px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }

        &.icd-unfulfilled {
          .icd-condition span {
            color: $colorIndicatorYellow;
          }
        }

        &.icd-fulfilled {
          .icd-condition span {
            color: $colorIndicatorGreen;
          }
        }
      }
    }
  }

  &:hover {
    /* cursor: pointer; */

    .content {
      .title {
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;

        .condition {
          display: block;
        }
      }

      .critical-icds {
        border-top-left-radius: 0;
        border-top-right-radius: 0;

        display: flex;
        line-height: inherit;

        li:not(:last-child) {
          margin-bottom: 1rem;
        }
      }
    }
  }

  &.green {
    .content {
      box-shadow: none;

      .title .criticality {
        color: $colorIndicatorGray;
      }
    }

    pointer-events: none;
  }

  &.yellow {
    .content .title .criticality {
      color: $colorIndicatorYellow;
    }
  }

  &.red {
    .content .title .criticality {
      color: $colorIndicatorRed;
    }
  }
}


one
two
three

Create a country drop-down field [duplicate]

While solving problem I got error after writing code:
chrome headless Alert function function should generate a alert FAILED
TypeError: Cannot read property ‘value’ of null
please help to solve this.

I tried the following code:

function runlist(){

  var name=document.getElementById("myname").value;
  var phone=document.getElementById("myphone").value;
  var country=document.getElementById("mycountry").value;
  var email=document.getElementById("mymail").value;
  var result = name + ','+phone+','+country+','+email;

  alert(result);  
  return result;
}

This is the code to stop zoomin of browser using controll+scroll

import { useEffect } from "react";
import "./styles.css";

export default function App() {
  useEffect(() => {
    const handleWheel = (e) => {
      if (e.ctrlKey || e.metaKey) e.preventDefault();
      console.log(e);
    };
    window.addEventListener("wheel", handleWheel, { passive: false });
    return () => {
      window.removeEventListener("wheel", handleWheel, { passive: true });
    };
  }, []);

  return (
    <div className="App">
      <div className="hover">Hover me </div>
    </div>
  );
}

Can someone explain me what is the roll of {passive:false} in this code
or{passive:true} in the code

How do I change a button’s href based on input?

I’ve been trying to make a comparison in JavaScript that alters the href based on the variables that I have in my code but I keep trying to make changes but the page never changes.

HTML

<a href=""> <button type = "submit">Log In</a> </button>
<script type="text/javascript" src="js/Login.js"></script>

JavaScript

var Username=document.getElementById("username");
var Password=document.getElementById("password");

function Login() {
  if(Username.value == "Lilen")&&(Password.value == "ILoveCapeYork22"){
  document.getElementById(LoginID).href="Citizen.html";
}
if(Username.value == "KitOne")&&(Password.value == "jwUw2umsR35N2uxf"){
  document.getElementById(LoginID).href="Admin.html";
 }
}

Basic Simple Remembering Theme allowing use of root:{} CSS Filters (based on an Advanced Auto Theme Selector)

Given a brilliant automatic theme selector that remembers the user’s set theme as asked in this question and elaborated in this answer (the one awared with a bounty which is carried over to GitHub).

What I really love about that answer, is the fact that the CSS theme-names do not need to be manually written down in some array in the javascript code, which makes that answer less prone to mistakes in the future!

(Despite the fact that it was not asked in the question, I can see how most people in the community do like to use the answer’s elegant solution of an automatical theme selector based on the users default OS theme of “light” or “dark”.)

However, I would really like a less complicated, more basic version of said answer, with just one default root:{} theme, unless and untill the user selects any of the other theme options. I do not wish or need an automatic light/dark selection or an “auto” theme option. Aside the default root: {} theme, only the user’s custom overriding manual choice should change the theme which then must be remembered by local storage.

Because I would like the default theme to be plain root: {}, because sothat when setting CSS Filters, such as filter: saturation or filter: grayscale, then everything in the page, images, tables, logo’s, everything, is affected by the selected theme color and css filter, and Not just background color and foreground color.

For this I have the following CSS which needs to be respected as a given:

CSS

:root{ /* Default Theme, if nothing is selected */
    --bgr: #eee;
    --txt: #000;
    --flt: none;
}
:root.blackwhite{
    --bgr: #fff;
    --txt: #000;
    --flt: contrast(100%) grayscale(100%);
}
:root.sepia {
    --bgr: lightblue;
    --txt: red;
    --flt: sepia(75%);
}
:root.holiday{
    --bgr: #fba;
    --txt: #269;
    --flt: blur(.25px) saturate(4);
}
:root.moody{
    --bgr: green;
    --txt: yellow;
    --flt: drop-shadow(16px 16px 20px yellow) blur(1px);
}

html { /* Have something to test */
  background: var(--bgr);
  color: var(--txt);
  filter: var(--flt); /* important filter that affects everything on the webpage */
}
h1{
    background: var(--bgr);
    color: var(--txt);
    }

theme{ /* my html element that contains only SVG graphics */
    display: flex;
    flex-direction: row;
}

HTML

<!-- this HTML structure is deliberate and needs to remain unchanged -->
<theme>
    <svg id="blackwhite"><rect width="100" height="50" /></svg>
    <svg id="sepia"><rect width="100" height="50" /></svg>
    <svg id="holiday"><rect width="100" height="50" /></svg>
    <svg id="moody"><rect width="100" height="50" /></svg>
</theme>
<h1>Click on a theme to change the color scheme!</h1>
<p>Some Paragraph texts.</p>
<img src="clouds.jpg" alt="clouds"/>

I want the much more elegant and logical <theme> and not an equally meanigless <some-div id="theme"> as container, since both do not have any semantic meanig. Some day in the future this html element could see the dawn of adoption and that trend starts here! Nothing beats the non-ambiguity of a logical html element.


In summary, the answer must meet the following criteria:

  • Respect the provided CSS and HTML code above
  • Be inspired by the css theme-name-free javascript answer already provided
  • Strip down all “auto” and “light/dark” theme autoselection from code
  • Respect the one CSS root:{}` as the one and only default theme
  • Only change theme if user clicks on the svg or if a theme is already in memory

prevent re render component using React and React-memo

I would like to prevent component re-rendering using React. I’ve read some guides but I’m still having trouble getting my code to work.
The CreateItem component creates an input form from the json object. When the input states change, React re-renders all components. I would avoid this situation as it causes some problems.

I have used React.memo but my code still doesn’t work. Is this a good way to implement this code? How can I correct my code? Thank you


function MyComponent() {
    
    return(
        <div className="row"> 
            {Array.from(new Map(Object.entries(json))).map((data) => (
                <CreateItem obj={data} />

            ))}

        </div>
    );
        
}



//function CreateDiv(props) {
const CreateDiv = React.memo((props) => {

    console.log("rendering ");

    return (
        <form name="myForm"  onSubmit= {formSubmit}>
            <div className="row">
                {Array.from(new Map(Object.entries(props.obj[1]))).map((data) => (
                <>
                {(() => { 
                     return(
                        <div className="col-sm-2">
                            <CreateItem obj={data[1]} />
                        </div>
                    )
                })()}
                </>
                ))}
            </div>
        </form>
    ); 
});

Input changes not being picked

I am using jquery to create a pop dialog in a page. The user is entering some text in the dialog inputs and based on this I am calling to a servlet. The thing is that somehow, I can’t get the inputs content everytime. I am trying to also get the change event for the input and when is not working, is not even triggering the events, but like I said, not sure why sometimes is not working. After calling the servlet and returning it works as expected, it only fails the first time (and not always).

This is my code JS:



$(function()
{
  //$.fn.bootstrapBtn = $.fn.button.noConflict();
  document.body.style.cursor = 'default';
  var dialog, form, product= $( "#product"), documentType= $( "#documentType"), docId = $( "#docId"), description= $( "#description"), docNameWithSpace = $("#docNameWithSpace"), name = $("#name"), documentTypeId = $( "#documentTypeId" ), projectTrackerPrefix = $ ("#projectTrackerPrefix"), allFields = $( [] ).add( projectTrackerPrefix, documentTypeId, product, documentType, name, description, docNameWithSpace);
  dialog = $( "#dialog-form" ).dialog(
  {
    autoOpen: false,
    height: 400,
    width: 480,
    modal: true,
    buttons: {
      "Create Document": createDocument,
      Cancel: function() {
        dialog.dialog( "close" );
      }
    },
    close: function() {
      form[ 0 ].reset();
      document.getElementById("dialogForm").reset();
      $("#spaces option:selected").each(function () {
               $(this).removeAttr('selected');
        });
      allFields.removeClass( "ui-state-error" );
    }
  });

  form = dialog.find( "form" ).on( "submit", function( event )
  {
    event.preventDefault();
    createDocument();
    return true;
  });

  function createDocument()
  {

    var title = description.val();

    var result= checkValidChars(document.getElementById("description").value);
    if(!result)
    {
      document.body.style.cursor = 'wait';
      document.getElementById("docTitle").value=document.getElementById("description").value;
      var var1 = document.getElementById("description").value;
      var var2 = document.getElementById("docTitle").value;
      alert("1->"+var1);
      alert("2->"+var2);
      document.getElementById("removeOutgoingLinks").value = ""+document.getElementById("removeOutgoingLinksCheck").checked;
      document.getElementById("keepRelativeLinks").value = ""+document.getElementById("keepRelativeLinksCheck").checked;
      $("#createDocForm").submit();
    }
  }

});

This is the HTML one:


<div id="dialog-form" title="Create New Document">
  <form id="dialogForm">
    <fieldset>

      <input type="hidden" name="product" id="product" value="" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important;" disabled="disabled">
      <input type="hidden" name="documentType" id="documentType" value="" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important;" disabled="disabled">
        <input type="hidden" name="docId" id="docId" value="" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important;" disabled="disabled">
      <input type="hidden" name="documentTypeId" id="documentTypeId" value="" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important;" disabled="disabled">
      <input type="hidden" name="projectTrackerPrefix" id="projectTrackerPrefix" value="$currProject.getTrackerPrefix()" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important;" disabled="disabled">


      <label for="id">Selected Documents</label>
      <textarea type="text" name="selectedDocs" id="selectedDocs" value="" class="text" style="color: -internal-light-dark-color(rgb(84, 84, 84), rgb(170, 170, 170)) !important; background-color: -internal-light-dark-color(rgb(235, 235, 228), rgb(45, 45, 45)) !important; width: 95%; padding: .4em; height:100px;" disabled="disabled"/>

      <label for="id">Description</label>
      <input type="text" name="description" id="description" class="text">

      <label for="removeOutgoingLinksCheck">Remove Outgoing Links from Document</label>
      <input type="checkbox" name="removeOutgoingLinksCheck" id="removeOutgoingLinksCheck">

      <label for="keepRelativeLinksCheck">Keep relative Work Item links between reused Documents</label>
      <input type="checkbox" name="keepRelativeLinksCheck" id="keepRelativeLinksCheck" checked="checked">

      <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>
</div>

Sometimes it works the first time, sometime it doesn’t. After returning from the servlet is always working. I have even tried to add onchange events and also
$("#description").on("input",function(e) { but they are not being reached, meaning that somehow is consistent in not detecting the changes, however, the user is entering text….

How to include a .js file into html page with webpack and electron-forge?

How to include a .js file into html page with webpack and electron-forge?

‘html` page :

<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>

    <div id="app"></div>

    <div class='viewer' id='viewer' title="MainPage" width= "480" height="480">

    <script> const global = globalThis; </script>
    <script src="./file-to-import.js"></script>
    <script>
    </script>

    <style>
     </style>

  </body>
</html>

I’ve added an entry point in package.json :

           "entryPoints": [
            {
              "html": "./src/app/index.html",
              "js": "./src/app/renderer.ts",
              "preload": {
                "js": "./src/main/preload/preload.ts"
              },
              "name": "main_window"
            },
            {
              "html": "./src/app/index.html",
              "js": "./src/app/file-to-import.js",
              "preload": {
                "js": "./src/main/preload/preload.ts"
              },
              "name": "main_window"
            },

And I also added a copy-path to webpack.plugins.js :

new CopyPlugin({
    patterns: [
      {
        from: path.resolve(__dirname, "./src/app/file-to-import.js"),
        to: path.resolve(__dirname, ".webpack/renderer/main_window/file-to-import.js")
      }
    ]
  })

In .webpack/renderer/main_window the file file-to-import.js is present :

(base) raphy@pc:~/Playground/.webpack/renderer/main_window$ ls -lah
total 716K
drwxrwxr-x 2 raphy raphy 4.0K Jun 13 13:44 .
drwxrwxr-x 4 raphy raphy 4.0K Jun 13 13:44 ..
-rw-rw-r-- 1 raphy raphy   60 Jun 13 13:44 file-to-import.js
-rw-rw-r-- 1 raphy raphy  409 Jun 13 13:44 index.html
-rw-rw-r-- 1 raphy raphy 554K Jun 13 13:44 index.js
-rw-rw-r-- 1 raphy raphy 141K Jun 13 13:44 preload.js

but I still get failed to load resource :
enter image description here

What am I doing wrongly? How to correctly load the file into the html page?

msg.edit is not a function in discord.js v13

I’m trying to assign a message to variable using let msg = message.channel.send({content: "bla-bla-bla"}); and if conditions are correct – edit it using msg.edit(), but I get msg.edit is not a function error as result! I’m aware you can use .then(), but in my situation I’m not editing this message right after sending it, so I can’t use .then()! Is there any alternative?

Problems using a js module is ts project

I have a react ts project where I installed a pure js module: crypto-prices. Considering this module doesn’t have any @types source, I created a decs.d.ts file with:

declare module "crypto-prices"

This removes the IDE issue. Yet, when I try to use the cryptoPrice modules through

import cryptoPrice from 'crypto-prices'

I get the following error:

Can't resolve 'crypto-prices' in ...

how can i delay the server request if its being sent repeatedly in Reactjs?

I have a checkbox input for a to-do-list app and, when I mark the task as done a request, will be sent to the server to update it
but I think it can slow down the server as you can check and uncheck the input repeatedly
so is there any way to delay the requests? for example, 300ms after the checkbox is changed
here is my code

const [todos, setTodos] = React.useState([]);

const completedOnChangeHandler = (e, id) => {
    const x = e.target.checked;
    console.log(x);

    axios
      .patch(`http://127.0.0.1:8000/todo/todos/${id}/`, {
        completed: x,
      })
      .then(
        (response) => {
          console.log(response.data);

          setTodos([response.data]);
        },
        (error) => {
          console.log(error);
        }
      );
  };

return (
    <form>
          {todos.map((todo) => (
            <ul key={todo.id}>
              <li>{todo.title}</li>
              <li>{todo.description}</li>
              <button>delete</button>
              <input
                type="checkbox"
                placeholder="completed"
                onChange={(e) => completedOnChangeHandler(e, todo.id)}
                checked={todo.completed}
              />
            </ul>
          ))}
    </form>
  );
};

export default Form;

Looking for regex that perform search from string by ignoring HTML tags that is available in long string

Example: a string contains html tags

string to highlight = "<p>Edit the (<i>Expression & Text</i>) to <span>see matches</span>"

Case 1:

  • Search phrase = "to see"
  • Expected output = "<p>Edit the (<i>Expression & Text</i>) <mark>to</mark> <span><mark>see</mark> matches</span>"

Case 2:

  • Search phrase = “to see”
  • Expected output = "<p>Edit <mark>the (</mark><i><mark>Expression</mark> & Text</i>) to <span>see matches</span>"

My Current code:

function markSearchString(stringToHilight, searchPhrase) {
`const mark = (str, pre = '', post = '') => `${pre}<mark class="highlight-`search">${content}</mark>${post}`;  //use this to apply mark tag on str

 

return stringToHilight.toString().split(new RegExp('(</?.*?>)', 'gi')).map(function (value) {
//check array index value is not HTML tag, if not check for match, if matched then apply for mark tag
        if (!new RegExp('(</?.*?>)', 'gi').test(value) && value && searchPhrase.test(value))
            return value.toString().replace(searchPhrase, (a) => m(a));
        return value;
    }).join(" ");
}

But the problem with the current code is that it only search in array index, if searched value is combination of 2 or 3 array index value in which on index value is HTML tag got fails

Your contribution is appreciated
Thanks

Slide effect in slider using jQuery

I have this slider

Demo link:

https://jsfiddle.net/rocks111/6pefLsc0/9/

Code:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
-
</style>
</head>
<body>

<div class="slideshow-container">

<div class="mySlides">
  <q>I love you the more in that I believe you had liked me for my own sake and for nothing else</q>
  <p class="author">- John Keats</p>
</div>

<div class="mySlides">
  <q>But man is not made for defeat. A man can be destroyed but not defeated.</q>
  <p class="author">- Ernest Hemingway</p>
</div>

<div class="mySlides">
  <q>I have not failed. I've just found 10,000 ways that won't work.</q>
  <p class="author">- Thomas A. Edison</p>
</div>

<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>

</div>

<div class="dot-container">
  <span class="dot" onclick="currentSlide(1)"></span> 
  <span class="dot" onclick="currentSlide(2)"></span> 
  <span class="dot" onclick="currentSlide(3)"></span> 
</div>

<script>
var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";  
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";  
  dots[slideIndex-1].className += " active";
}
</script>

</body>
</html> 

I want to give slide effect rather than hiding and showing the slides array. If i click on next button the old slides should move towards right of the screen and new slide should display from extreme left of the screen.