Dropdown is getting highlighted

When I click the submit button, my spinner appears, but in the background, my dropdown field is becoming highlighted.

I believe this could be happening because, when compared to another component, we have a date field with a white background. Upon closer inspection, it seems the dropdown has a grey background. As a result, when the spinner appears, it gets highlighted.

I might be mistaken, so I’m seeking a solution to prevent the dropdown from being highlighted.

Below is my code for dropdown:

<div id="xyzDropdown" class="dropdown">
        <select id="xyzReports" name="reportType">
            <c:forEach var="report" items="${xyzReport}">
                <option value="${report}">${report}</option>
            </c:forEach>
        </select>
    </div>

And here is btn:

<input id="submitButton" class="disabledbtn" disabled type="button"
        value="button" />

Initial picture

After Submit btn clicked

Not able to user select entered text in v-select search

I have custom v-select search in vuetify.
When i enter text in v-text-field and try to select and clear the entered text, its not allowing to select

Below is the code snippet

 <template v-slot:prepend-item>
  <div class="fruit-search-box">
    <v-text-field hide-details placeholder="Search" />
  </div>
</template>

And below is the playground link to replicate the issue.
playground link

Resolution: User should be able to enter and select text from the v-text-filed.

How to fill each form with the scanned passport data?

This is a form where we scan the passport for each passenger and the rest of the fields get filled automatically

import PropTypes from 'prop-types'
import React, { useEffect, useRef, useState } from 'react'
import Stack from '@kiwicom/orbit-components/lib/Stack/index'
import InputField from '@kiwicom/orbit-components/lib/InputField/index'
import useTranslate from '@kiwicom/orbit-components/lib/hooks/useTranslate'
import { getIn, useFormikContext } from 'formik'
import InputFile from '@kiwicom/orbit-components/lib/InputFile'
import Select from '@kiwicom/orbit-components/lib/Select'
import { GDS_CABIN_CLASSES } from '../../../../../constants/support'
import { useSelector } from 'react-redux'
import { gdsAvailableSeatsDatabase } from '../../../../../shared/utils'
import Translate from '@kiwicom/orbit-components/lib/Translate'
import { Overlay, ViewerWrapper, Body, ImageOuter } from '../../../../../routes/SamplePage/styles'
import moment from 'moment'
import { scanImage, scanPdf } from '../../../../../util/mrzReader'
import {
  Alert,
  Button,
  Modal,
  ModalFooter,
  ModalHeader,
  ModalSection,
} from '@kiwicom/orbit-components'

const parseDate = (yymmddDate) => {
  if (!yymmddDate) {
    return ''
  }
  return moment(yymmddDate, 'YYMMDD', 'fr').format('DD MMM YYYY')
}

const preScanImageFirstRender = (imgObject) => {
  if (imgObject) {
    const { clientWidth, clientHeight } = imgObject
    return {
      orentation: clientWidth > clientHeight ? 'landscape' : 'portrait',
      renderWidth: clientWidth,
      renderHeight: clientHeight,
      width: 'not calculated',
      height: 'not calculated',
    }
  }

  return {}
}

const IFRAME_PROCESS = true
const GdsFormFields = ({ passengerIndex, form, passengersType, onCabinChange }) => {
  const shoppingCart = useSelector((state) => state.gdsBookings.cart)
  const translate = useTranslate()
  const cabinClassOptions = GDS_CABIN_CLASSES.map((cabin) => ({
    label: translate(cabin),
    value: cabin,
    disabled: gdsAvailableSeatsDatabase(shoppingCart?.flight, shoppingCart?.trip_type, cabin) === 0,
  }))
  const { setFieldValue, values } = useFormikContext()
  useEffect(() => {
    // At this point firstName it's updated with the lastest user input
  }, [values[`passengers.${passengersType}.${passengerIndex}.cabin_class`]])
  const [rotageAngle, setRotateAngle] = useState(0)
  const [showPreview, setShowPreview] = useState(false)
  const [fileData, setFileData] = useState({})
  const [toggleWith, setToggleWidth] = useState({ width: 0, height: 0 })
  const [ocrData, setOcrData] = useState({})
  const [passportModal, setPassportModal] = useState(false)
  const inputRef = useRef(null)
  const imgRef = useRef(null)
  const iframeRef = useRef(null)

  const handleRotate = (evt) => {
    evt.preventDefault()
    setRotateAngle(rotageAngle + 90)
    const { width, height } = toggleWith
    setToggleWidth({ width: height, height: width })
  }

  const [imgSrc, setImgSrc] = useState(null)
  const [imgUrl, setImgUrl] = useState(null)

  const handleRetake = (evt) => {
    evt.preventDefault()
    if (fileData.url) {
      URL.revokeObjectURL(fileData.url)
      setFileData({})
      inputRef.current.value = ''
      inputRef.current.click()
    }
    setOcrData({})
    return true
  }

  const updateInfo = (info) => {
    const { scanStatus, data } = info || {}
    const passengerDataKey = `passengers.${passengersType}.${passengerIndex}`
    if (scanStatus === 'success') {
      if (data && data.parsed && data.parsed.fields) {
        const passportData = { ...data.parsed.fields }
        passportData.birthDate = parseDate(passportData.birthDate)
        passportData.expirationDate = parseDate(passportData.expirationDate)
        setOcrData({ scanStatus, passportData })
        setPassportModal(true)
        form.setFieldValue(`${passengerDataKey}.first_name`, passportData.firstName)
        form.setFieldValue(`${passengerDataKey}.last_name`, passportData.lastName)
        form.setFieldValue(`${passengerDataKey}.passport_nbr`, passportData.documentNumber)
        const formattedBirthDate = moment(passportData.birthDate, 'DD-MMM-YYYY').format(
          'YYYY-MM-DD',
        )
        form.setFieldValue(`${passengerDataKey}.birth_date`, formattedBirthDate)
        const formattedPassportExp = moment(passportData.expirationDate, 'DD-MMM-YYYY').format(
          'YYYY-MM-DD',
        )
        form.setFieldValue(`${passengerDataKey}.passport_expire_at`, formattedPassportExp)
        console.log('Ocr data ' + JSON.stringify(ocrData, null, 't'))
      } else {
        setOcrData({ scanStatus, error: 'No OCR Information' })
      }
    }
    if (scanStatus === 'progress') {
      setOcrData({ scanStatus, status: data })
    }
    if (scanStatus === 'error') {
      setOcrData({ scanStatus, error: 'Error in file scan' })
    }
    if (scanStatus === 'default') {
      setOcrData({ scanStatus, error: 'Unknown error' })
    }
    if (scanStatus !== 'progress') {
      setShowPreview(false)
    }
  }

  const processOCR = () => {
    let postData = {}
    if (fileData.type && fileData.type.indexOf('pdf') > 0) {
      if (!IFRAME_PROCESS) {
        scanPdf(fileData.url, updateInfo)
      }
      postData = { action: 'SCAN_PDF', payload: { url: fileData.url } }
    } else {
      if (!IFRAME_PROCESS) {
        scanImage(fileData.url, updateInfo)
      }
      postData = { action: 'SCAN_IMAGE', payload: { url: fileData.url } }
    }
    if (!IFRAME_PROCESS) {
      return false
    }
    const iframeContentWindow = iframeRef.current.contentWindow
    iframeContentWindow.postMessage(postData)
  }

  useEffect(() => {
    if (fileData.url && fileData.url.length > 0) {
      setShowPreview(true)
      setTimeout(() => {
        const { renderWidth: width, renderHeight: height } = preScanImageFirstRender(imgRef.current)
        setToggleWidth({ width, height })
      }, 500)
    } else {
      setShowPreview(false)
    }
  }, [fileData])

  const receiveMessage = (evt) => {
    if (evt.data) {
      const { action, payload } = evt.data || {}
      if (action === 'SENDING_OCR_DATA') {
        updateInfo(payload.ocrData)
      }
    }
  }

  useEffect(() => {
    setTimeout(() => {
      window.addEventListener('message', receiveMessage, false)
    }, 200)

    return () => {
      window.removeEventListener('message', receiveMessage, false)
    }
  }, [])

  const handleFileInputChange = (event) => {
    const file = event.target.files[0]
    const fileUrl = URL.createObjectURL(file)
    setFileData({
      url: fileUrl,
      type: file.type,
    })
    setImgUrl(fileUrl)
    form.setFieldValue(`passengers.${passengersType}.${passengerIndex}.passport_scan`, file)
  }
  return (
    <>
      {passengersType === 'adults' && passengerIndex === 0 && (
        <>
          <Stack
            spaceAfter="large"
            key={passengerIndex}
            direction="row"
            spacing="medium"
            align="center"
          >
            <InputField
              placeholder={translate('package.passenger.email')}
              name={`passengers.${passengersType}.${passengerIndex}.email`}
              value={form.values.passengers[passengersType][passengerIndex].email}
              type="email"
              inputMode="email"
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              error={
                getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.email`) &&
                getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.email`)
                  ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.email`)
                  : null
              }
            />
            <InputField
              placeholder={translate('package.passenger.phone')}
              name={`passengers.${passengersType}.${passengerIndex}.phone`}
              value={form.values.passengers[passengersType][passengerIndex].phone}
              type="text"
              inputMode="tel"
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              error={
                getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.phone`) &&
                getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.phone`)
                  ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.phone`)
                  : null
              }
            />
          </Stack>
          <hr className="border" />
        </>
      )}
      <Stack spaceAfter="large" direction="row" spacing="medium" align="center">
        <Select
          options={cabinClassOptions}
          placeholder={translate('gds.passenger.cabin_class')}
          name={`passengers.${passengersType}.${passengerIndex}.cabin_class`}
          value={form.values.passengers[passengersType][passengerIndex].cabin_class}
          inputMode="text"
          onChange={(event) => {
            form.setFieldValue(
              `passengers.${passengersType}.${passengerIndex}.cabin_class`,
              event.target.value,
            )
            onCabinChange(event.target.value, passengersType, passengerIndex)
          }}
          onBlur={form.handleBlur}
          error={
            getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.cabin_class`) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.cabin_class`)
              ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.cabin_class`)
              : null
          }
        />
      </Stack>
      <Stack flex direction="row" grow align="start" spaceAfter="medium" key={passengerIndex}>
        <InputFile
          placeholder={translate('package.pic.format')}
          fileName={
            form.values.passengers[passengersType][passengerIndex].last_name +
              ' ' +
              form.values.passengers[passengersType][passengerIndex].passport_nbr ||
            translate('package.pic.format')
          }
          buttonLabel={translate('package.passenger.passport_scan')}
          allowedFileTypes={['.png', '.jpg', '.jpeg']}
          name={`passengers.${passengersType}.${passengerIndex}.passport_scan`}
          value={form.values.passengers[passengersType][passengerIndex].passport_scan}
          onChange={handleFileInputChange}
          ref={inputRef}
          onRemoveFile={() =>
            form.setFieldValue(`passengers.${passengersType}.${passengerIndex}.passport_scan`, null)
          }
          onBlur={form.handleBlur}
        />
        <div>
          {IFRAME_PROCESS ? (
            <iframe
              width="0"
              height="0"
              ref={iframeRef}
              src="ocr-frame/ocr.html"
              title="ocr-processor"
            />
          ) : null}
        </div>
        {ocrData.error ? <p style={{ color: 'red' }}> {ocrData.error}</p> : null}
        <>{imgSrc && <img src={imgSrc} alt="" />}</>
        {ocrData && ocrData.scanStatus === 'success' && ocrData.passportData && passportModal ? (
          <>
            <Modal onClose={() => setPassportModal(false)}>
              <div
                style={{
                  textAlign: 'left',
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                <ModalHeader
                  title={
                    <div style={{ display: 'flex', justifyContent: 'center' }}>
                      <Translate tKey="profile.personal_info" />
                    </div>
                  }
                >
                  <div style={{ display: 'flex', justifyContent: 'center' }}>
                    {fileData.url && fileData.type && fileData.type.indexOf('pdf') === -1 ? (
                      <img src={fileData.url} width="600" alt="preview passport" />
                    ) : null}
                  </div>
                </ModalHeader>
                <ModalSection>
                  <Alert spaceAfter="medium">
                    <Translate tKey="confirm.passport.alert" />
                  </Alert>
                  {Object.keys(ocrData.passportData).map((itemKey, index) => (
                    <>
                      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        {itemKey === 'issuingState' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="passport.issuing_state" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'lastName' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="user.last_name" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'firstName' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="user.first_name" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'documentNumber' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="passport.document_number" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'nationality' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="form.nationality" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'birthDate' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="form.birth" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'sex' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="form.gender" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                        {itemKey === 'expirationDate' && (
                          <div key={index}>
                            <div style={{ display: 'flex' }}>
                              <span className="passport-scan-info">
                                <Translate tKey="form.expiry" />
                              </span>
                              <span className="passport-scan-info">
                                {ocrData.passportData[itemKey]}
                              </span>
                            </div>
                          </div>
                        )}
                      </div>
                    </>
                  ))}
                </ModalSection>
                <ModalFooter>
                  <Button onClick={() => setPassportModal(false)}>
                    <Translate tKey="app.confirm" />
                  </Button>
                </ModalFooter>
              </div>
            </Modal>
          </>
        ) : null}
        {showPreview && fileData.url ? (
          <Overlay>
            <ViewerWrapper>
              <header style={{ display: 'flex', justifyContent: 'space-around' }}>
                <Button onClick={handleRotate}>
                  <Translate tKey="app.rotate" />
                </Button>
                <Button
                  onClick={() => {
                    setShowPreview(false)
                  }}
                >
                  <Translate tKey="app.close" />
                </Button>
              </header>
              <Body loading={ocrData.scanStatus === 'progress' ? 'loaging' : ''}>
                <ImageOuter angle={rotageAngle} toggleWith={toggleWith}>
                  <div className="img-inner">
                    {fileData.type && fileData.type.indexOf('pdf') === -1 ? (
                      <img id="previewImage" src={fileData.url} alt="user uploads" ref={imgRef} />
                    ) : null}
                  </div>
                </ImageOuter>
              </Body>
              <footer style={{ display: 'flex', justifyContent: 'space-around' }}>
                <Button onClick={handleRetake}>
                  <Translate tKey="app.retake" />
                </Button>
                <Button primary onClick={processOCR}>
                  <Translate tKey="app.use" />
                </Button>
              </footer>
            </ViewerWrapper>
          </Overlay>
        ) : null}
      </Stack>
      <Stack spaceAfter="large" direction="row" spacing="medium" align="center">
        <InputField
          placeholder={translate('package.passenger.first_name')}
          name={`passengers.${passengersType}.${passengerIndex}.first_name`}
          type="text"
          value={form.values.passengers[passengersType][passengerIndex].first_name}
          inputMode="text"
          onChange={(event) => {
            const uppercaseValue = event.target.value.toUpperCase()
            form.setFieldValue(
              `passengers.${passengersType}.${passengerIndex}.first_name`,
              uppercaseValue,
            )
          }}
          onBlur={form.handleBlur}
          error={
            getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.first_name`) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.first_name`)
              ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.first_name`)
              : null
          }
        />
        <InputField
          placeholder={translate('package.passenger.last_name')}
          name={`passengers.${passengersType}.${passengerIndex}.last_name`}
          value={form.values.passengers[passengersType][passengerIndex].last_name}
          type="text"
          inputMode="text"
          onChange={(event) => {
            const uppercaseValue = event.target.value.toUpperCase()
            form.setFieldValue(
              `passengers.${passengersType}.${passengerIndex}.last_name`,
              uppercaseValue,
            )
          }}
          onBlur={form.handleBlur}
          error={
            getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.last_name`) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.last_name`)
              ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.last_name`)
              : null
          }
        />
      </Stack>
      <Stack spaceAfter="large" direction="row" spacing="medium" align="center">
        <InputField
          label={translate('package.passenger.birth_date')}
          inlineLabel
          placeholder={translate('package.passenger.phone')}
          name={`passengers.${passengersType}.${passengerIndex}.birth_date`}
          value={form.values.passengers[passengersType][passengerIndex].birth_date}
          onChange={form.handleChange}
          onBlur={form.handleBlur}
          type="date"
          error={
            getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.birth_date`) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.birth_date`)
              ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.birth_date`)
              : null
          }
        />
        <InputField
          placeholder={translate('package.passenger.passport_number')}
          name={`passengers.${passengersType}.${passengerIndex}.passport_nbr`}
          value={form.values.passengers[passengersType][passengerIndex].passport_nbr}
          type="passportid"
          inputMode="numeric"
          onChange={form.handleChange}
          onBlur={form.handleBlur}
          error={
            getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.passport_nbr`) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.passport_nbr`)
              ? getIn(form.errors, `passengers.${passengersType}.${passengerIndex}.passport_nbr`)
              : null
          }
        />
      </Stack>

      <Stack spaceAfter="large" direction="row" spacing="medium" align="center">
        <InputField
          label={translate('package.passenger.passport_expire_at')}
          inlineLabel
          placeholder={translate('package.passenger.passport_expire_at')}
          name={`passengers.${passengersType}.${passengerIndex}.passport_expire_at`}
          value={form.values.passengers[passengersType][passengerIndex].passport_expire_at}
          onChange={form.handleChange}
          onBlur={form.handleBlur}
          type="date"
          error={
            getIn(
              form.errors,
              `passengers.${passengersType}.${passengerIndex}.passport_expire_at`,
            ) &&
            getIn(form.touched, `passengers.${passengersType}.${passengerIndex}.passport_expire_at`)
              ? getIn(
                  form.errors,
                  `passengers.${passengersType}.${passengerIndex}.passport_expire_at`,
                )
              : null
          }
        />
      </Stack>
    </>
  )
}
export default GdsFormFields

GdsFormFields.propTypes = {
  form: PropTypes.any.isRequired,
  passengerIndex: PropTypes.number.isRequired,
  passengersType: PropTypes.string.isRequired,
}

The problem when I scan the passport in the first form it also fill the second form’s details, while I only want it to fill the first one (where I uploaded the passport pic). How to make it so that every form fills the info of the passport pic I passed to it ?

Proper pattern to give nested React components control of a global function

I have an application which has a global “event listener” of sorts. When a barcode is scanned, the global function keypresser.enter is called, with the string of the barcode as the argument. EG if you scan "1111", it will call keypresser.enter("1111");

Right now, my application isn’t written in React, but I’ve been considering trying to write it in React. However, handling this function in a situation with nested React components, each of which needs might sometimes need to have control of what happens when keypresser.enter is called, has been puzzling me.

So right now, in my non-react code, any time I have a Screen that is the main UI element at that moment in time, it can define keypresser.enter = value => ... and do whatever it wants with a scanned value. There’s only ever one function – the barcode scan only ever has to trigger one behaviour at any given time.

But with React, my questions are regarding (a) when and where to register this function, and (b) if I need any kind of clever logic to involve de-registering the keypresser.enter function when a screen dismounts?

EG imagine I have a situation where I’m on a screen where someone can scan something, but that screen can also sometimes show another element, and when that element is showing, that element should have control of the keypresser.enter function – but once that element is gone, it should revert back to the parent screen. Is there a good pattern in react for handing control of a function like this to a child, only when that child is showing?

parsing with requests and BeautifulSoup . Why the email cannot be scraped from the link

my script is not returning email field that I want to scrape from a website . Any workaround??

from  bs4 import BeautifulSoup

import requests

url = 'https://www.kw.com/agent/UPA-6587385179144187908-1'

res = requests.get(url)

soup = BeautifulSoup(res.content,'html.parser')

name  = soup.find('div',class_='AgentContent__name').text.strip()

location = soup.find('div',class_='AgentContent__location').text.strip()

website = soup.find('a',class_='AgentInformation__factBody').attrs['href']

print(website)

print(name)

print(location)

This is what I get

/cdn-cgi/l/email-protection#f18394909d94828590859482b199949895989093949d94df929e9c

Heidi Abele

Campbell, CA

Increase the FPS in requestanimationframe() javascript

 function animate4() {
   ctx.clearRect(0, 0, cw, ch)

   gamearray.forEach((layer) =>{
      layer.update()
   })

   if (paause === true) {
      return
   }else {
      requestAnimationFrame(animate4)
   }
 } 



 animate4()

this code runs 60 times a second but i want to be able to increase the FPS

What im trying to do is let the users choose diff FPS to run the game at without the game speeding up.

I tried to search for it in here obv but the answers are not very clear for me and the answers were for a diff problem that was also releated to requestanimationframe timing

Replace all the values using JS in d365 crm

I have an “command” entity. In command entity I have a field called “command Text”. It contains Values like “Hello User Please Reply “. Now I want to replace the dynamic values which is present with <> to actual values.

I have below code to replace the values, but it is not actually replacing.

I want the output like “Hello User Please Reply Mathew 25”. Instead I’m getting the “Hello User Please Reply Mathew Hello User Please Reply 25”.

I tried all the ways I can. But not able to fix it. I need to complete it immediately. I would appreciate anyone’s help.

The sample code is below.

retrieveAndReplaceDynamicFieldValues: function (formContext, fieldName, commandText, English, NonEnglish, Language) {
    var replacedValues = "";
    var completedIterations = 0;
    Xrm.WebApi.retrieveMultipleRecords("templatefield", "?$select=entity,fieldschemaname&$filter=name eq '" + fieldName + "'").then(
        function success(templatefields) {
            // Columns
            templatefields.entities.forEach(function (TemplateResult) {
                 var entityName = TemplateResult["[email protected]"].toLowerCase(); 
                var fieldSchemaName = TemplateResult["fieldschemaname"]; // Text

                var RecordGUID = retrieveGuid(formContext, entityName);

                Xrm.WebApi.retrieveRecord(entityName, RecordGUID, "?$select=" + fieldSchemaName).then(
                    function success(result) {
                        // Get the value of the field
                        var fieldValue = result[fieldSchemaName];
                        // Replace the field value in the command text
                        commandText = commandText.replace(new RegExp(fieldName, 'gi'), fieldValue);

                        replacedValues = commandText;
                        // Increment the completedIterations counter
                        completedIterations++;
                        // Check if this is the last iteration, then update SMS body
                        if (completedIterations === templatefields.entities.length) {
                            updateBody(English, NonEnglish, Language, commandText);
                        }

                        
                    },
                    function error(error) {
                        console.error("Error retrieving Campaign record: " + error.message);
                    }
                );
            });
        },
        function error(error) {
            console.error("Error retrieving SMS template field: " + error.message);
        }
    );
    updateBody(English, English, Language, replacedValues);
},

In update body method I’m setting the replaced values. Always template filed count is 1 because we are having at least one dynamic value.

Please Help me to achieve this asap.

How to apply this interesting animation on navigation bar? [closed]

The navigation bar is transparent, when scrolled down, it disappears with subtle animation, when scrolled up, it appears with white background and if we keep scrolling it becomes sticky until we reach the top, now its white background turns transparent again. See here.

I looked into this script, but since I know nothing of jQuery, I was unable to figure it out, I did find the relevant snippet, but don’t know how does all this work.

Please help me achieve the same effect on my navigation bar.

Many thanks!

Why doesn’t object show when using map [closed]

const infoContents = homepagedata.contentItems.contentItem
<div className='bg-slate-400 w-90p flex'>
                    {
                        infoContents.map((infoData) => {
                            <h1 key={infoData.id} className='text-black'>
                                {
                                    infoData.title
                                }
                            </h1>
                        })
                    }
</div>

Doesn’t show an H1.

However, if I console.log it, it shows just fine.

{
                        
     infoContents.map((infoData) => { console.log(infoData.title) })
    
}

enter image description here

ReactJS Sweep Line Demo: Issue with Multiple Surfaces Not Updating Simultaneously

I need to make a demo of a sweep line with multiple surfaces with reactjs, but The problem is that when I choose to show more than 1 surface it only plays on the data on the latest created surface and stops drawing data on the old surfaces.

you can see the example here with the code: https://28zf6p.csb.app/

this is a GIF for the problem:
enter image description here

note: the reason I need multiple surfaces is that I want to have the charts draggable with sortableJS to follow the design I got.

Looking for help trying to open a simple HTML page [closed]

I’m very interested in this project: https://github.com/BlondeauJulien/dart-scoring
But I am unable to make it work.
It is a simple webpage that lets you keep track of darting scores, I would love to run this on a simple webserver to use at home.

I thought it would be as simple as download the files and open a index.html since all should run locally, but I get an empty page…
Any ideas? I’m not strong enough with my coding skills.

Edit: Not sure why this was closed, I am not seeking for a recommendation at all. I am fairly sure I want this specific product to work in my situation.

How to add field belonging to a date?

I want user to select month and year. On 1 column, there would be days[eg: 1-30] of month they selected. User then can add Habits on other columns. I want those user to be able to put ‘X’ in that row of the date[eg: 29, X, X, , X], those columns being Date, Habit1, Habit2, Habit3, Habit4.

I am stuck on what to do ahead.

import React, { useState } from 'react';
import './HabitTable.css';

function HabitTable() {

  const today = new Date();
  const todayDate = today.getDate();
  const daysArray = [];

  const [month, setMonth] = useState('');
  const [year, setYear] = useState('');
  const [dateArray, setDateArray] = useState([]);
  const [dailyHabits, setDailyHabits] = useState([]); 

  const [addHabit, setAddHabit] = useState('');

  function addHabits() {
    if (addHabit.trim() !== '') {
      const updatedHabits = [...dailyHabits];
      updatedHabits.push(addHabit);
      setDailyHabits(updatedHabits);
      setAddHabit(''); 
    }
  }

  function getCorrectDates(month, year) {
    const numDays = new Date(year, month, 0).getDate();

    for (let i = 0; i < numDays; i++) {
      daysArray[i] = i + 1;
    }

    return daysArray;
  }

  function handleDates() {
    setDateArray(getCorrectDates(month, year));
  }

  return (
    <div>
      <div className='select-dates'>
        <input placeholder='month' onChange={(e) => setMonth(e.target.value)} />
        <input placeholder='year' onChange={(e) => setYear(e.target.value)} />
        <button onClick={handleDates}>Submit</button>
      </div>

      <div>
        <h1>Days</h1>
        <div>
          <input placeholder='add habit' value={addHabit} onChange={(e) => setAddHabit(e.target.value)} />
          <button onClick={addHabits}>Add</button>
        </div>
        <div className='days'>
          {dateArray.map((day) => (
            <div key={day}>
              <input disabled placeholder={day} />
            </div>
          ))}
          {Object.keys(dailyHabits).map((habitKey) => (
            
            <input key={todayDate} placeholder={dailyHabits[habitKey] + todayDate} />
          ))}
        </div>
      </div>
    </div>
  );
}

How to exclude (-) sign by appending it to the next operand when 2 or more operators are entered consecutively in a operation?

I am working on a calculator app using ReactJS. Most of the things are working expectedly. However I want the (-) sign to be appended to the next operand when 2 or more operators are entered consecutively e.g., something like this should happen: the sequence “5 * – 5” = should produce an output of “-25” : rather than ‘0’.
Below is the snippet for reference

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previous: "",
      current: "",
      operation: "",
    };
  }

  clear = () => {
    this.setState(() => ({
      previous: "",
      current: "0",
      operation: null,
    }));
  };

  delete = () => {
    this.setState((prevState) => ({
      current: prevState.current.slice(0, -1),
    }));
  };

  appendNumber = (number) => {
    const { current } = this.state;
    if (current === "0") {
      this.delete();
    }
    if (number === "." && current.includes(".")) return;
    this.setState(
      (prevState) => ({
        current: prevState.current + number,
      })
    );
  };

  chooseOperation = (op) => {
    const { previous, current, operation } = this.state;
    if (previous !== "" && current !== "") {
      this.compute();
    }

    // if (operation !== "" && op === "-" && previous !== "") {
    //   this.setState((prevState) => ({
    //     current: "-",
    //     operation: prevState.operation,
    //   }));
    // } else {

    this.setState(
      (prevState) => ({
        operation: op,
        previous:
          prevState.current === "" ? prevState.previous : prevState.current,
        current: "",
      })
    );

    // }
  };

  compute = () => {
    let computation;
    const { previous, current, operation } = this.state;
    const prev = parseFloat(previous);
    const curr = parseFloat(current);
    if (isNaN(previous) || isNaN(current)) return;
    let factorial = (n) => (n === 1 ? n : n * factorial(n - 1));
    switch (operation) {
      case "+":
        computation = prev + curr;
        break;
      case "-":
        computation = prev - curr;
        break;
      case "*":
        computation = prev * curr;
        break;
      case "÷":
        computation = prev / curr;
        break;
      case "!":
        computation = factorial(prev);
        break;
      case "√":
        computation = Math.sqrt(prev);
        break;
      case "log":
        computation = Math.log(prev);
        break;
      case "sin":
        computation = Math.sin(prev * (Math.PI / 180));
        break;
      default:
        return;
    }

    this.setState({
      current: computation,
      operation: "",
      previous: "",
    });
  };

As you can see in the commented portion of chooseOperation method I tried to implement the said logic by conditionally updating the state parameters, here is how it looked like

chooseOperation = (op) => {
    const { previous, current, operation } = this.state;
    if (previous !== "" && current !== "") {
      this.compute();
    }

    if (operation !== "" && op === "-" && previous !== "") {
      this.setState((prevState) => ({
        current: "-",
        previous: prevState.previous,
        operation: prevState.operation,
      }));
    } else {
      this.setState(
        (prevState) => ({
          operation: op,
          previous:
            prevState.current === "" ? prevState.previous : prevState.current,
          current: "",
        })
      );
    }
  };

However I am getting errors with this version. Even though I was able to perform a simple calculation like ‘8 * – 5 = -40’,but the program failed on longer operations containing chained operations.

Jest unit testing for React router is failing

I have a simple React component like this (Location.tsx)

import React from "react";
import { useLocation } from "react-router-dom";

const Location: React.FC = () => {
  const location = useLocation();
  console.log(location);

  return <p>Testing useLocation</p>;
};

export default Location;

And im writing the unit test case for this one in Location.test.js like this

import {Location} from "../Location.tsx";
import { Router } from "react-router-dom";
// other code like describe here

  it("Testing useLocation", async () => {
    const component = render(
      <Router>
        <Location />
      </Router>
    );

    expect(component).toBeDefined();
    }

Im getting this error “Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.“. This happens only when we add the Router wrapper in the test case and if we remove that im getting the below error

TypeError: (0 , _reactRouterDom.useLocation) is not a function

Any suggestion to make this work is appreciated.

version using is "react-router-dom": "6.4.2"

Update : the issue is because of this line in the Location.tsx

const location = useLocation();