How to filter through cards based on the value using onChange when selected in a dropdown

This is how I filter to get the string of objects from an array of objects displayImages which I got the the value of dropdown

  const locationNameDropdown = () => {
    return displayImages.map((data, key) => (
      <option key={key} value={data.locationName}>
        {data.locationName}
      </option>
    ));
  };

Here is my {onChange}

 const onChange = (e) => {
    if (e.target.value === "All") {
      setDisplayImages(null);
    } else {
      setDisplayImages([e.target.value]);
    }
  };

This is my card display

 const images = displayImages.map((data, key) => {
    return (
      <div key={key}>
        <div className="card bg-light mb-3" value={data.locationName}>
          <div className="card-header">
            <center>
              <h5>{data.locationName}</h5>
            </center>
          </div>
          <div className="card-body">
            <div className="mrtgDiv">
              <img src={data.filePath}  />
            </div>
          </div>
        </div>
      </div>
    );
  });

and this is the return

  return (
    <div>
      <div>
        <select className="form-select" onChange={onChange}>
          <option value="All" defaultValue>
            All
          </option>
          {locationNameDropdown()}
        </select>
      </div>
      <br />
      <br />

      <center>
        <h5>test</h5>
      </center>
      <div>{images}</div>
    </div>
  );

when I select the first item in the dropdown, I only get a blank card that has no value and when I select the “All” value I receive null I don’t know what to put in the IF ELSE

I want to display the images in a card that I select

HTML auto update select box

So I am writing code for people management webpage. All the result are generated by SQL, now I use Jquery to get result from Java Spring. The problem is I can save it into a JS list and make the update as a function, but I don’t know how I can update my select box.

For example, I got a JS list like this {“tom”,”jerry”}, what I want to have on HTML is enter image description here

and I run the function update() [when clicked a button called “update”]

the list become {“tom”,”jerry”,”spike”}

what I want to have now is enter image description here

so what should I do to achieve this on HTML using tag? Is their any specific data structure to achieve this?

the resource can be used to build this are

a list {"tom","jerry"}
and a function update()

how to make a payment gateway for cart with multiple items in react

I am using razorpay api as a payment gateway for my shopping website and I am stuck at creating multiple orders

it works perfectly fine when I order single product but when I try to checkout from cart where there are multiple product added, I get stuck about what to do for amount and description field because it sends array of product while its send single product when its ordered directly.

app.post("/payment", async (req, res) => {
  try {
    const { product } = req.body;
    console.log("product");
    const amount = product.price * 100;
    const currency = "INR";
    const receipt = product.id;
    const notes = { desc: product.desc };

    instance.orders.create({ amount, currency, receipt, notes }),
      (err, order) => {
        if (error) {
          return res.status(500).json({ err });
        }
        return res.status(200).json({ order });
      };
  } catch (err) {
    console.log(err);
  }
  res.json(res);
});

when I order directly

{
 b_name: "siyaram",
 id: 9,
 p_color: "white",
 p_img: {type: 'Buffer', data: Array(5771)},
 p_name: "kurta",
 p_price: 1000,
 p_size: "s m l"
}

when I order from cart

[
 {
  b_name: "raymond,
  id: 9,
  p_color: "yellow",
  p_img: {type: 'Buffer', data: Array(5771)},
  p_name: "kurta",
  p_price: 1000,
  p_size: "s m l"
 },
 {
  b_name: "peter England",
  id: 9,
  p_color: "red",
  p_img: {type: 'Buffer', data: Array(5771)},
  p_name: "kurta",
  p_price: 1300,
  p_size: "s m l"
 }
]

this throws an error cause here I have multiple product.

In ios, when getUserMedia is called again, the existing stream is killed

Problems with iPad using Safari with video chat app. We want to present the user’s video feed and provide the ability to select their own webcam device in a pop-up window. However, to show the selected webcam device, the video of the selected webcam is displayed in a pop-up window, but the original camera feed turns black and the audio is cut off. This seems to happen when calling navigator.mediaDevices.getUserMedia().

my code to get the device

const constraints = {
        speaker: {deviceId: audioOutputSelect.value ? {exact: audioOutputSelect.value} : undefined},
        audio: {deviceId: audioInputSelect.value ? {exact: audioInputSelect.value} : undefined},
        video: {deviceId: videoSelect.value ? {exact: videoSelect.value} : undefined}
    };
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
    ...
})

The biggest problem is that the audio of the existing video disappears.

How to make drag drop stay at dropped place after page refresh

Can someone please help me!

I am working on assignment with drag & drop and localstorage.
This is my first time wring a code involving localstorage. I’m creating
someting like kanban board.

The problem I am having right now is, I have no idea how am i going
to write code for getItem and make my card stay at the position where i drop
it after page refresh. I already write for setItem part and I think it works.
I can see the position change in the localstorage everytime I change it’s place.
Here is what i’ve tried so far

const todos = document.querySelectorAll(".todo");
const all_status = document.querySelectorAll(".box")


todos.forEach((todo) => {
  todo.addEventListener("dragstart", dragStart);
  todo.addEventListener("dragend", dragEnd);
});

function dragStart() {
  draggableTodo = this;
  setTimeout(() => {
    this.style.display = "none";

  }, 0);
  console.log("dragStart");
}

function dragEnd() {
  draggableTodo = null;
  setTimeout(() => {
    this.style.display = "block";

  }, 0);
  console.log("dragEnd");
}

all_status.forEach((box) => {
  box.addEventListener("dragover", dragOver);
  box.addEventListener("dragenter", dragEnter);
  box.addEventListener("draleave", dragLeave);
  box.addEventListener("drop", dragDrop);
});

function dragOver(e) {
  e.preventDefault();
  //console.log("dragOver");
}

function dragEnter() {
  console.log("dragEnter");
}

function dragLeave() {
  console.log("dragLeave");
}

function dragDrop() {
  this.appendChild(draggableTodo);
  var left = this.offsetLeft;
  var top = this.offsetTop;
  localStorage.setItem("left", left);
  localStorage.setItem("top", top);
  console.log("localStorage");
}

jsfiddle

Any A/B testing method for Javascript file that is embedded on third-party domains? [closed]

I’m developing a web product that will be embedded on third-party websites (across domains).
The product is served as a JS file and enables a widget to pop up at websites.
I’d like to improve the effect of service by testing widget appearance across domains.

So the question is, what would be a possible solution for A/B testing for scripts that is embedded across domains?

Though Google Optimize is a great A/B testing tool, it’s not applicable for third-party websites.
I think widget-like services are getting more and more common (such as Intercom and Zendesk), so there would be some good solutions. (Or these players individually implement A/B testing for themselves?)

Any good ideas?

how to remove highlight from only one selection using mark.js

I’ve created a form that highlights matching text on entered in a textarea on the page as you make selections on the checkboxes. It seems to work properly when you are checking the checkboxes, but as soon as you have more then one checkbox checked and then uncheck a single checkbox, all highlights get removed. I would like it to only remove the highlight of the unchecked box when it is changed from checked to unchecked.

I’m fairly new to JavaScript so I’m not sure if I’m missing something obvious here or not but I am stumped as to why I’m getting this behavior.

Here is an example function handling the highlight on a single checkbox. You can see my full code in the JS fiddle link here:
https://jsfiddle.net/gosem01/kf8az926/1/

function highlightArrowsOnCheck() {
  var instanceArrows = new Mark(highlightedParagraph);
  var options = {
    "debug": true,
    "log": window.console
  };

  if (checkedArrows.checked) {
    instanceArrows.markRegExp(/«|»/g, options);
  } else {
    instanceArrows.unmark(options);
  }
}

mark.js docs:
https://markjs.io/

How to pass the parameter to datetime picker function

As i had a datetimepicker function, and i need to iterate through an array which contains dates and then i need to add those dates with additional 15 minutes or 20 minutes based on some conditions,

what i need is , how to pass the array values(dates) to the datetimepicker and to add the minutes to that dates

previously my code was

 $(".addtime").datetimepicker({
 ignoreReadonly:true,
  format: 'LT',
  defaultDate: generateCurrentDate()+' 00:20'
});

as it adding for current date, i need to pass input as params and then i has to add to that , how to achieve this

Check if Number in minutes is a hour mark (60..120..180.. 240 mins etc) [duplicate]

Question

Figure out if a minute number is the exact number leading into an hour / hours.

Description

I have no code examples, as its something I’m trying to figure out.

I’m trying to build a script that basically returns true or false if the amount of seconds leads into an hour or x hours ; otherwise if not it returns false.

I’m unsure exactly how this should work, as it basically just all the time should check if the amount of minutes – would be the exact minutes to lead into an hour.. (This being 1 hour, 2 hours, 3 hours, 4 hours….. and so on)

I do not need to know how many hours it is or anything; i just need to know if its true or false if the amount of minutes would be exact to Is the amount of minutes an exact hour hour timers.

Expected Workflow examples

The minute number is just a const/let/var input being (example: 59, 60, 120, 300, 673)

If Minute Number is 0-59 Return false

If Minute Number is 60 Return true (Because this would be 1 Hour)

If Minute Number is 60-119 Return false

If Minute Number is 120 Return true (Because this would be exact 2 Hours)

If Minute Number is 121-179 Return false

If Minute Number is 180 Return true (Because this would be exact 3 Hours)

… and so on, basically endless – it just has to return true on any exact is minute an hour part, otherwise false.

My thoughts i had to complete, but not sure

I would guess you would need to check if the minute number is divded by 60 or something like that; but im unsure.

Hope someone is able to help me out, thank you in advance.

How to move the objects to the top inside array based on the matched key

I have an array of objects with different keys i want to move the objects to the top based on the key i want.

Given array based on the status: “Active” I want all the matched objects to be moved top

[{name: "abc", age: "20", status: "Active"}, {name: "xyz", age: "21", status: "Inactive"}, {name: "pqr", age: "22", status: "Active"}]

Expected Output:

[{name: "abc", age: "20", status: "Active"}, {name: "pqr", age: "22", status: "Active"}, {name: "xyz", age: "21", status: "Inactive"}]

Ace Editor: Lock or Readonly Code Segment That Comes After

I’m currently studying Ace Editor, and I would like to make a kind of Terminal or Console, I found this topic that is the way, but I’m still lost on how to block everything that comes back and only release from the symbol ” : ” to the user to type what they need, hit Enter and break the line and theoretically the code would be executed.

the topic in question is this, but unfortunately it doesn’t solve my problem in question

does anyone know how I could do this kind of thing in Ace Editor with JS Vanilla in a not so complex way?

would like to have something like this or similar, using Ace-editor

findOneAndUpdate returns with error “Query for sharded findAndModify must contain the shard key”

My query is a java script file that gets the variables from a caller bash script:

findOneAndUpdate({“id”: ObjectId(doc_id)}, {$set: { “attributes.StudentNo”: student_no + “” + epoch + “_” + curr_date } });

When I run the query I get this error:

2022-01-13T15:35:32.421+1100 E QUERY [js] uncaught exception:
Error: findAndModifyFailed failed: {
“ok” : 0,
“errmsg” : “Query for sharded findAndModify must contain the shard key”,
“code” : 61,
“codeName” : “ShardKeyNotFound”,
“operationTime” : Timestamp(1642048532, 11),
“$clusterTime” : {
“clusterTime” : Timestamp(1642048532, 11),
“signature” : {
“hash” : BinData(0,”WdMSDpXqoDKFTAGrFh0epHq2qCQ=”),
“keyId” : NumberLong(“7010334517764292616”)
}
} } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13 DBCollection.prototype.findAndModify@src/mongo/shell/collection.js:725:15
DBCollection.prototype.findOneAndUpdate@src/mongo/shell/crud_api.js:900:12
@js/db_update_dups.js:1:1 2022-01-13T15:35:32.421+1100 F –
[main] failed to load: js/db_update_dups.js
2022-01-13T15:35:32.421+1100 E – [main] exiting with code -3

There is shard field in the document. Should I include that in the query? If yes,
how will be my query?

how to get Matching string present in array in javacsript

I have an array –

const a = ['first','test','second','test1','test2,'test3','last','now',get']

I have test,test1,test2,test3. I want to get index of test3 using test then dynamic number. How can I do this ?

First we have to check if test is present in array then get indexOf test otherwise get index of test1,test2,test3,test4 dynamically. We don’t know what will be the dynamic number in test keyword. But yes dynamic number would be consecutive like 1,2,3,4 or 3,4,5,6

disable another button on react js

i have a react project which has three buttons in it. when a button is clicked, for example the second button, it will log “this is from button two ” followed by a random number with time interval 500ms. my aim is when i click a button, another buttons will be disabled, how to do this? thanks in advance.

this is my App.js

import './App.css';
import { Button1 } from './Button1.React';
import { Button2 } from './Button2.React';
import { Button3 } from './Button3.React';

function App() {
  
    return (
      <div className="App">
        <Button1>log one</Button1>
        <Button2>log two</Button2>
        <Button3>log three</Button3>
      </div>
    );
  
  
}

export default App;

this is my Button1.React.jsx

import React from "react";

export const Button1 = ({
    children,
    type,
    doStuff1 = ()=> {
        console.log("this is button one ", Math.random().toFixed(1));
        setTimeout(doStuff1, 500);
      },
})=>{
    return (
        <button onClick={doStuff1} type={type}>
        {children}
        </button>
    )
};

this is my Button2.React.jsx

import React from "react";

export const Button2 = ({
    children,
    type,
    doStuff2 = ()=> {
        console.log("this is button two ", Math.random().toFixed(1));
        setTimeout(doStuff2, 500);
      }
})=>{
    return (
        <button onClick={doStuff2}type={type}>
        {children}
        </button>
    )
};

this is my Button3.React.jsx

import React, { Children } from "react";

export const Button3 = ({
    children,
    type,
    doStuff3 = ()=> {
        console.log("this is button three ", Math.random().toFixed(1));
        setTimeout(doStuff3, 500);
      }
})=>{
    return (
        <button onClick={doStuff3}type={type}>
            {children}
        </button>
    )
};

and here’s the screenshot from the rendered page
enter image description here

i’ve been told to do this is using useState that returns a boolean condition to disable/enable click, but i don’t know how to do this.

How to Access This.props.route.params in constructor

my first page pushing an array with some data to next page ,I want to use that data in RenderItem for flatlist.I tried bind event but its also not worked for me ,any help would be appriciated .

enter code here
export default class mainPage extends React.Component<any, any> {

  constructor(props: any) {
    super(props)
    this.state = {
      text: '',
      slots: [],
      screen: 'screen1',
      vehicleNumber: '',
      parkingLot: [],
      selectedSlot: '',
    }
  }

  createSlot() {
    let tempdata: any[] = []
    for (let i = 0; i < parseInt(this.state.text); i++) {
      tempdata.push({
        allocated: false,
        timestamp: new Date(),
      })
    }
    this.setState(
      {
        slots: [
          ...this.state.slots,
          {
            id: (Math.random() + 1).toString(36).substring(7),
            count: parseInt(this.state.text),
            data: tempdata,
          },
        ],
        text: '',
        screen: 'screen2',
      },
      () => {
        this.props.navigation.navigate('floor', {
          slots: this.state.slots,
        })
      },
    )
  }
  // componentDidMount() {

  //   this.setState({ parkingLot: [...this.parkingLot] })

  // }
  park = () => {
    console.log('jcjhj', this.state.parkingLot)
    var item = this.state.slots[
      Math.floor(Math.random() * this.state.slots.length)
    ]
    console.log('Parkinglot', this.state.parkingLot, item)
    console.log('Slots', this.state.slots)
    if (this.state.slots) {
    }

    // this.setState({
    //   parkingLot: [
    //     ...this.state.parkingLot,
    //     { carnumber: this.state.vehicleNumber },
    //   ],
    // })
  }
  renderItem(item: any) {
    return (
      <TouchableOpacity
        style={styles.Slotinput}
        onPress={() =>
          this.setState({ screen: 'screen3', selectedSlot: item.id })
        }
      >
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot ID:-{item.id}
        </Text>
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot Count:-{item.count}
        </Text>
      </TouchableOpacity>
    )
  }
  renderItem1(item: any) {
    return (
      <View style={styles.Slotinput}>
        <Text>{item.allocated ? 'Allocated' : 'Available'}</Text>
        {this.state.parkingLot.map((e: any) => {
          return <Text>{e.carnumber}</Text>
        })}
      </View>
    )
    //   )
    // }
    // return demo
  }

  render() {
    return (
      <View>
        {this.state.screen === 'screen1' && (
          <View style={styles.form}>
            <TextInput
              style={styles.input}
              placeholder="Enter A value for slot"
              onChangeText={(text: any) => this.setState({ text })}
              value={this.state.text}
            />
            <TouchableOpacity
              style={
                this.state.text && this.state.text
                  ? styles.addItemButton
                  : styles.BlurItemButton
              }
              disabled={this.state.text == ''}
              onPress={() => this.createSlot()}
            >
              <Text style={styles.buttonText}>Submit</Text>
            </TouchableOpacity>
          </View>
        )}
        {/* {this.state.screen === 'screen2' && (
          <>
            <Text onPress={() => this.setState({ screen: 'screen1' })}>
              Back
            </Text>
            <FlatList
              data={this.state.slots}
              renderItem={({ item }) => this.renderItem(item)}
              keyExtractor={(item) => item.id}
            />
          </>
        )} */}
        {/* {this.state.screen === 'screen3' && (
          <>
            <Text onPress={() => this.setState({ screen: 'screen2' })}>
              Back
            </Text>
            <>
              {}
              <TextInput
                placeholder="Vechicle Number"
                style={styles.input}
                value={this.state.vehicleNumber}
                onChangeText={(vehicleNumber: any) =>
                  this.setState({ vehicleNumber })
                }
                // onChangeText={data => this.setState({ vehicleNumber: data })}
              ></TextInput>
            </>

            <TouchableOpacity
              style={styles.addItemButton}
              onPress={() => this.park()}
            >
              <Text>Park Vechicle</Text>
            </TouchableOpacity>

            {this.state.slots
              ?.filter((i: any) => i.id === this.state.selectedSlot)
              ?.map((item: any, index: number) => {
                return (
                  <View key={index}>
                    <FlatList
                      data={item.data}
                      renderItem={({ item }) => this.renderItem1(item)}
                      keyExtractor={(item, index) => index.toString()}
                    />
                  </View>
                )
              })}
          </>
        )} */}
      </View>
    )
  }
}

Here is my floor.tsx page(next page)

enter code here
export default class floor extends Component<any, any> {
handleslot: any
constructor(props: any) {
super(props)
// console.log(‘SLOTDATA::–‘, props.route.params)

    this.state = {
      text: '',
      slots: [],
      screen: 'screen1',

      selectedSlot: '',
    }
    // let slo: Array<any> = this.props.route.params
    // console.log('propdata-->', slo)
    // this.setState({
    //   slo: [],
    // })
  }

  renderItem=(item: any)=> {
    console.log('item', item)

    return (
      <TouchableOpacity
        style={styles.Slotinput}
        onPress={() =>
          this.setState({ screen: 'screen3', selectedSlot: item.id })
        }
      >
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot ID:-{item.id}
        </Text>
        <Text style={{ fontSize: 12, color: 'white', fontWeight: 'bold' }}>
          Slot Count:-{item.count}
        </Text>
      </TouchableOpacity>
    )
  }
  render() {
    return (
      <View>
        <Text onPress={() => this.props.navigation.goBack()}>Back</Text>

        <FlatList
          data={this.props.route.params}
          renderItem={({ item }) => 
          this.renderItem(item)}
          keyExtractor={(item) => item.id}
        />
      </View>
    )
  }
}