how change class component of image slider to functional component and how can custom auto slide to manual press to slide

I need to change this image slider class component to functional component


import * as React from "react";
import { StyleSheet, View, ScrollView, Dimensions, Image } from "react-native";

const DEVICE_WIDTH = Dimensions.get("window").width;

class BackgroundCarousel extends React.Component {
  scrollRef = React.createRef();
  constructor(props) {
    super(props);

    this.state = {
      selectedIndex: 0
    };
    this.scrollRef = React.createRef();
  }

  componentDidMount = () => {
    setInterval(() => {
      this.setState(
        prev => ({
          selectedIndex:
            prev.selectedIndex === this.props.images.length - 1
              ? 0
              : prev.selectedIndex + 1
        }),
        () => {
          this.scrollRef.current.scrollTo({
            animated: true,
            x: DEVICE_WIDTH * this.state.selectedIndex,
            y: 0
          });
        }
      );
    }, 3000);
  };

  setSelectedIndex = event => {
    const contentOffset = event.nativeEvent.contentOffset;
    const viewSize = event.nativeEvent.layoutMeasurement;

    // Divide the horizontal offset by the width of the view to see which page is visible
    const selectedIndex = Math.floor(contentOffset.x / viewSize.width);
    this.setState({ selectedIndex });
  };

  render() {
    const { images } = this.props;
    const { selectedIndex } = this.state;
    return (
      <View style={{ height: "100%", width: "100%" }}>
        <ScrollView
          horizontal
          pagingEnabled
          onMomentumScrollEnd={this.setSelectedIndex}
          ref={this.scrollRef}
        >
          {images.map(image => (
            <Image
              style={styles.backgroundImage}
              source={{ uri: image }}
              key={image}
            />
          ))}
        </ScrollView>
        <View style={styles.circleDiv}>
          {images.map((image, i) => (
            <View
              style={[
                styles.whiteCircle,
                { opacity: i === selectedIndex ? 0.5 : 1 }
              ]}
              key={image}
              active={i === selectedIndex}
            />
          ))}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  backgroundImage: {
    height: "100%",
    width: Dimensions.get("window").width
  },
  circleDiv: {
    position: "absolute",
    bottom: 15,
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    height: 10
  },
  whiteCircle: {
    width: 6,
    height: 6,
    borderRadius: 3,
    margin: 5,
    backgroundColor: "#fff"
  }
});

export { BackgroundCarousel };

When I change this, I have error.


import React ,{useState,useEffect} from 'react'
import { StyleSheet, View, ScrollView, Dimensions, Image } from "react-native";

const DEVICE_WIDTH = Dimensions.get("window").width;

const BackgroundCarousel =({ images })=>{
   // const isCarousel = React.useRef(null)
    const scrollRef = React.useRef();
   const[selectedIndex,setSelectedIndex]=useState(0);

//  useEffect(()=>{
//     setInterval(() => {
//         this.setState(
//           prev => ({
//             selectedIndex:
//               prev.selectedIndex === this.props.images.length - 1
//                 ? 0
//                 : prev.selectedIndex + 1
//           }),
//           () => {
//             this.scrollRef.current.scrollTo({
//               animated: true,
//               x: DEVICE_WIDTH * this.state.selectedIndex,
//               y: 0
//             });
//           }
//         );
//       }, 3000);
//  })
 

//   componentDidMount = () => {
//     setInterval(() => {
//       this.setState(
//         prev => ({
//           selectedIndex:
//             prev.selectedIndex === this.props.images.length - 1
//               ? 0
//               : prev.selectedIndex + 1
//         }),
//         () => {
//           this.scrollRef.current.scrollTo({
//             animated: true,
//             x: DEVICE_WIDTH * this.state.selectedIndex,
//             y: 0
//           });
//         }
//       );
//     }, 3000);
//   };
useEffect(()=>{
    setSelectedIndex = event => {
        const contentOffset = event.nativeEvent.contentOffset;
        const viewSize = event.nativeEvent.layoutMeasurement;
    
        // Divide the horizontal offset by the width of the view to see which page is visible
        const selectedIndex = Math.floor(contentOffset.x / viewSize.width);
        this.setState({ selectedIndex });
      };
})

 

 
    return (
      <View style={{ height: "100%", width: "100%" }}>
        <ScrollView
          horizontal
          pagingEnabled
          onMomentumScrollEnd={selectedIndex}
          ref={scrollRef}
        >
          {images.map(image => (
            <Image
              style={styles.backgroundImage}
              source={{ uri: image }}
              key={image}
            />
          ))}
        </ScrollView>
        <View style={styles.circleDiv}>
          {images.map((image, i) => (
            <View
              style={[
                styles.whiteCircle,
                { opacity: i === selectedIndex ? 0.5 : 1 }
              ]}
              key={image}
              active={i === selectedIndex}
            />
          ))}
        </View>
      </View>
    );
  
}

const styles = StyleSheet.create({
  backgroundImage: {
    height: "100%",
    width: Dimensions.get("window").width
  },
  circleDiv: {
    position: "absolute",
    bottom: 15,
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    width: "100%",
    height: 10
  },
  whiteCircle: {
    width: 6,
    height: 6,
    borderRadius: 3,
    margin: 5,
    backgroundColor: "#fff"
  }
});

export { BackgroundCarousel };

here is homescreen

import { BackgroundCarousel } from "../components/BackgroundCarousel";

 <BackgroundCarousel images={[{uri : card.photo},{uri : card.photoo},{uri : card.photooo}]}/>

how can change to functional component and how can add press function to move image slider instead of auto slide by interval.
when press right corner , move to right and when press left corner ,move left.
please help me.

I want to access dom even in a modal with React-slick (useRef)

Currently, I’m using react-slick to implement it.
I want to access the slider dom with useref (ref.cuurent), but the moment the modal opens, it becomes null.
You can access it by sliding it.
I think it’s probably because I’m accessing it within a modal.
How do I get a ref.cuurent the moment the modal opens?


export const index: React.FC = () => {
    const [isShowHowToModal, setIsHowToModal] = useState(true)

    return (
        <Box>
            <div>hello</div>
            {isShowHowToModal && <Modal setIsHowToModal={setIsHowToModal} />}
        </Box>
    )
}



import Slider from 'react-slick'

export const Modal = React.FC<Props>(setIsModal) => {
  
  const onClickCancel = () => {
    setIsModal(false)
  }

  const refs = useRef<Slider>(null)
  console.log(refs)

  const settings = {
    dots: false,
    infinite: false,
    speed: 500,
    slidesToShow: 1,
    slidesToScroll: 1,
  }

  return (
    <Slider ref={refs} {...settings}>
      <div>aaa</div>
      <div>bbb</div>
      <div>ccc</div>
    </Slider>
}

It would be helpful if you could answer with the function component.

Button outcome is stacked on top of each other

I am currently making a calendar and would really appreciate some help as I am currently learning javascript by myself.

Whenever the month button is clicked, a new output is created and ‘stacked’ underneath the original entry. Is there a way to get the new month to replace the old one?

I have found problems online with button replacements but not code that includes multiple buttons / outputs.

Thanks for your help!! This is driving me crazy!!

<!DOCTYPE html> <!-- states the doctype -->
<html>
<head> <!-- heading -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
</head>
<h1>
Calendar
</h1>

<div id="info" class="btn-group" style="width:100%;">
  <button onclick="daysinmonth(0, 2021)" style="width:20%;">January</button>
  <button onclick="daysinmonth(1, 2021)" style="width:20%;">Febuary</button>
  <button onclick="daysinmonth(2, 2021)" style="width:20%">March</button>
  <button onclick="daysinmonth(3, 2021)" style="width:20%">April</button>
  <button onclick="daysinmonth(4, 2021)" style="width:20%">May</button>
  <button onclick="daysinmonth(5, 2021)" style="width:20%">June</button>
  <button onclick="daysinmonth(6, 2021)" style="width:20%">July</button>
  <button onclick="daysinmonth(7, 2021)" style="width:20%">August</button>
  <button onclick="daysinmonth(8, 2021)" style="width:20%">September</button>
  <button onclick="daysinmonth(9, 2021)" style="width:20%">October</button>
  <button onclick="daysinmonth(10, 2021)" style="width:20%">November</button>
  <button onclick="daysinmonth(11, 2021)" style="width:20%; margin-bottom:40px;">December</button>
</div>

<script>
function daysinmonth(month, year) {
  //clearit();
  var dt = new Date();
  dt.setMonth(month+1);
  dt.setFullYear(year);
  dt.setMonth(dt.getMonth(), 0);
  var lastday = dt.getDate();
  daystomonth(lastday, month, year)
}

function daystomonth(lastday, month, year) {
  dayslist = []
  const d = new Date(year, month, 1);
  var firstday = d.getDay();
  for (i = 1; i < lastday+1; i++) {
    dayslist[i-1] =+ i;
  }
  calender(firstday, dayslist, lastday)
}

function calender(firstday, dayslist, lastday) {
  const body = document.body,
    tbl = document.createElement('table');
    tbl.style.border = '1px solid black';
    tbl.style.boxSizing = 'border-box';

  var daysnames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"];
  var weekcount = 10; var count = 0;
  var daycount = firstday - 1;
  if (daycount == -1) { //Monday = 1
    daycount = 6;
  }

  for (let i = 0; i < weekcount; i++) {
    const tr = tbl.insertRow();
    if (i == 0) {
    for (let j = 0; j < 7; j++) {
      const td = tr.insertCell();
      td.appendChild(document.createTextNode(`${daysnames[j]}`));
      }
    }
    if (i == 1) {
      const tr = tbl.insertRow();
      for (let j = 0; j < 7; j++) {
        if (daycount <= j) {
          const td = tr.insertCell();
          td.appendChild(document.createTextNode(`${dayslist[count]}`));
          count = count + 1;
        } else {
          const td = tr.insertCell();
          td.appendChild(document.createTextNode(`  `));
        }
      }
    }
    if ( i > 1) {
      for (let j = 0; j < 7; j++) {
        if (count >= lastday) {
          const td = tr.insertCell();
          td.appendChild(document.createTextNode(`  `));
          count = count + 1;
        }
        else {
          const td = tr.insertCell();
          td.appendChild(document.createTextNode(`${dayslist[count]}`));
          count = count + 1;
        }
      }
    }
    if (count >= lastday) {
      weekcount = i + 1;
    } 
  }
  body.appendChild(tbl);
}
</script>

Is it possible to loop through a switch statement

I am making a standard slider which has two buttons to go through the images. However I want to make it modular. So that the end user can add 200 images if they like. I use Jquery to hide and show the images. But I don’t want to write 200 if statement, so I used a switch and wanted to loop through that switch which changes the cases active slide to display and hide the other element and stops if the amount of items has been reached.

But I have been having some issues, is there someone more experienced than me that can help

$('.slider-wrap').each( function() {
            let itemsAmount =  $('.slider-img', $(this)).length;
            console.log(itemsAmount);
        });


        let currentPic = 0;

        $('.sliderbuttonPlus').on('click', () => {
            currentPic++;

            let itemsAmount =  $('.slider-img', $('.slider-wrap')).length;
                        
            switch(currentPic) {

                case 0:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-0').css('display', 'block');
                break;

                case 1:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-1').css('display', 'block');
                break;

                case 2:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-2').css('display', 'block');
                break;

                case 3:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-3').css('display', 'block');
                break;

                case 4:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-4').css('display', 'block');
                break;

                case 5:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-5').css('display', 'block');
                break; 

                case 6:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-6').css('display', 'block');
                break;

                case 7:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-7').css('display', 'block');
                break;

                case 8:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-8').css('display', 'block');
                break;
                
                case 9:
                    $('.slider-img').css('display', 'none');
                    $('#slider-block-image-9').css('display', 'block');
                break;

            }   
                if(currentPic > itemsAmount) {
                        currentPic = itemsAmount;
                };

                console.log(currentPic);
        });
    

        $('.sliderbuttonMinus').on('click', () => {
            currentPic--;

        switch(currentPic) {
            case 0:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-0').css('display', 'block');
            break;
            case 1:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-1').css('display', 'block');
            break;
            case 2:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-2').css('display', 'block');
            break;
            case 3:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-3').css('display', 'block');
            break;
            case 4:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-4').css('display', 'block');
            break;
            case 5:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-5').css('display', 'block');
            break;   
            case 6:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-6').css('display', 'block');
            break;
            case 7:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-7').css('display', 'block');
            break;
            case 8:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-8').css('display', 'block');
            break;
            case 9:
                $('.slider-img').css('display', 'none');
                $('#slider-block-image-9').css('display', 'block');
            break;

        } 
        
        if (currentPic <= 0){
            currentPic = 0;
        };   
            console.log(currentPic);
        });

        if (currentPic === 0) {

            $('.slider-img').css('display', 'none');
            $('#slider-block-image-0').css('display', 'block');
            
        } 

        console.log(currentPic);     

    });

HTML displayed on the site

<div class="slider-wrap">
    <div class="button-wrap">
        <button class="sliderbuttonMinus">Links</button>
    </div>


        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/warhammer-1.jpg" alt="" id="slider-block-image-0" style="display: block;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/xcom-1.jpg" alt="" id="slider-block-image-1" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Skyrim-1.jpg" alt="" id="slider-block-image-2" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Skylines-1.jpg" alt="" id="slider-block-image-3" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Sea-of-thieves-1.jpg" alt="" id="slider-block-image-4" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Mario-1.jpg" alt="" id="slider-block-image-5" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Minecraft-1.jpg" alt="" id="slider-block-image-6" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Overwatch-1.jpg" alt="" id="slider-block-image-7" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/Half-life-1.jpg" alt="" id="slider-block-image-8" style="display: none;">


        
        <img class="slider-img" src="https://zelfbouwcontainer.online/wp-content/uploads/2021/11/hearthstone-1.jpg" alt="" id="slider-block-image-9" style="display: none;">


         <div class="button-wrap">      
        <button class="sliderbuttonPlus">Rechts</button>
    </div>     
</div>

PHP

<div class="slider-wrap">
    <div class="button-wrap">
        <button class="sliderbuttonMinus">Links</button>
    </div>

<?php
// Check rows exists.
if( have_rows('afbeeldingen_slider') ):

    $x = 0;
    // Loop through rows.
    while( have_rows('afbeeldingen_slider') ) : the_row();

        // Load sub field value.
        $image = get_sub_field('slider_image');
        $image_url = $image['url'];
        $image_alt = $image['alt'];
        ?>

        <img class="slider-img" src="<?php echo $image_url; ?>" alt="<?php echo $image_alt; ?>" id="slider-block-image-<?php echo $x?>">


        <?php
        // Do something...
        $x++;
    // End loop.
    endwhile;

// No value.
else :
    // Do something...
endif;


?> <div class="button-wrap">      
        <button class="sliderbuttonPlus">Rechts</button>
    </div>     
</div>

How can I execute some async tasks in parallel with limit in generator function?

I’m trying to execute some async tasks in parallel with a limitation on the maximum number of simultaneously running tasks.

There’s an example of what I want to achieve:

Task flow example

Currently this tasks are running one after another. It’s implemented this way:

export function signData(dataItem) {
  cadesplugin.async_spawn(async function* (args) {
    //... nestedArgs assignment logic ...

    for (const id of dataItem.identifiers) {
      yield* idHandler(dataItem, id, args, nestedArgs);
    }
    
    // some extra logic after all tasks were finished
  }, firstArg, secondArg);
}

async function* idHandler(edsItem, researchId, args, nestedArgs) {
  ...
  let oDocumentNameAttr = yield cadesplugin.CreateObjectAsync("CADESCOM.CPAttribute");
  yield oDocumentNameAttr.propset_Value("Document Name");
  ...
  // this function mutates some external data, making API calls and returns void
}

Unfortunately, I can’t make any changes in cadesplugin.* functions, but I can use any external libraries (or built-in Promise) in my code.

I found some methods (eachLimit and parallelLimit) in async library that might work for me and an answer that shows how to deal with it.

But there are still two problems I can’t solve:

  1. How can I pass main params into nested function?
  2. Main function is a generator function, so I still need to work with yield expressions in main and nested functions

There’s a link to cadesplugin.* source code, where you can find async_spawn (and another cadesplugin.*) function that used in my code.

That’s the code I tried with no luck:

await forEachLimit(dataItem.identifiers, 5, yield* async function* (researchId, callback) { 
  //... nested function code 
});

It leads to Object is not async iterable error.

Another attempt:

let functionArray = [];
dataItem.identifiers.forEach(researchId => {
  functionArray.push(researchIdHandler(dataItem, id, args, nestedArgs))
});
await parallelLimit(functionArray, 5);

It just does nothing.

Сan I somehow solve this problem, or the generator functions won’t allow me to do this?

I got different color about three js

enter image description here

enter image description here

When i use hex color into mesh, just like “#426158”, i got an color, then when i set a color object,like new Three.Color("#426158") into mesh, i got different color, who can help me?

First case:

export function NormalMesh() {
    let color = new THREE.Color("#426158")
    return <>
        <mesh position={[0,1,0]}>
            <boxGeometry/>
            <meshBasicMaterial color={color} />
        </mesh>
        
    </>
}

second case:

export function NormalMesh() {
    let color = new THREE.Color("#426158")
    return <>
        <mesh position={[0,1,0]}>
            <boxGeometry/>
            <meshBasicMaterial color={"#426158"} />
        </mesh>
        
    </>
}

i got different result.

How to Detect user if stopped at some unknown location base or a place from gps history data

I want to create a feature that contains the location history of the user itself every time it stops at a place.

For example, if the user stops at a location that I previously marked, it will display the name of the location, but if it stops at an unknown place, it will display the words “Unknown Stop”. Like the example below.

The following is an example of the location history of the user I have.

[{
"location": {
  "timestamp": 1640226572000,
  "fromMockProvider": false,
  "speedAccuracy": 3.0999999046325684,
  "speed": 2.126629114151001,
  "courseAccuracy": 60.29999923706055,
  "course": 335.00262451171875,
  "accuracy": 4.800000190734863,
  "altitudeAccuracy": 1.71183432826049805,
  "altitude": 6.099546432568,
  "longitude": 91.72313144,
  "latitude": 3.9974028
},
"device_information": "angelica ANGELICA Redmi",
"battery": 1},{
"location": {
  "timestamp": 1640226575000,
  "fromMockProvider": false,
  "speedAccuracy": 2.9000000953674316,
  "speed": 1.7470654249191284,
  "courseAccuracy": 67.80000305175781,
  "course": 318.0428161621094,
  "accuracy": 4.724999904632568,
  "altitudeAccuracy": 1.741869330406189,
  "altitude": 6.09213144568,
  "longitude": 91.7316444,
  "latitude": 3.9974605
},
"device_information": "angelica ANGELICA Redmi",
"battery": 1}]


//and more history in array

and the test code done, looks like it works with geolib library but has bugs in time

for (let i = 0; i < unknownArr.length; i++) {
    var dataPertama = unknownArr[i]
    var dataKedua = unknownArr[i + 1]
    if (dataKedua != undefined) {
        var selisihTotalKeduanya = hitungSelisihAngka(dataPertama.lama_unknown, dataKedua.lama_unknown)
        if (selisihTotalKeduanya > 10) {
            var jikaDekatToko = visitTimeArr.some(data => {
                var customerData = data.customer_data
                if (customerData.customer_latitude != null || customerData.customer_latitude != undefined) {
                    return isPointWithinRadius(
                        {
                            latitude: customerData.customer_latitude,
                            longitude: customerData.customer_longitude
                        },
                        {
                            latitude: dataPertama.start_unknown.location.latitude,
                            longitude: dataPertama.start_unknown.location.longitude
                        }, 100)
                } else {
                    return false
                }
            })
            var jikadiIntika = isPointWithinRadius(Strings.kordinatIntika, {
                latitude: dataPertama.start_unknown.location.latitude,
                longitude: dataPertama.start_unknown.location.longitude
            }, 100)

            if (!jikaDekatToko) {
                if (!jikadiIntika) {
                    response.push(unknownArr[i])
                } else {
                    var dataIntikaPertama = unknownArr.find(el => {
                        el.name = 'Intika'
                        return el !== undefined
                    })
                    response.push(dataIntikaPertama)
                }
            }
        }
    } else {
        var jikadiIntika = isPointWithinRadius(Strings.kordinatIntika, {
            latitude: dataPertama.start_unknown.location.latitude,
            longitude: dataPertama.start_unknown.location.longitude
        }, 100)
        if (!jikadiIntika) {
            response.push(unknownArr[i])
        } else {
            if (findFirstIntika) {
                var dataIntikaTerakhir = unknownArr[unknownArr.length - 1]
                if (dataIntikaTerakhir.name == 'Intika') {
                    response.push(dataIntikaPertama)
                }
            } else {
                var dataIntikaPertama = unknownArr.find(el => {
                    el.name = 'Intika'
                    return el !== undefined
                })
                response.push(dataIntikaPertama)
            }
        }
    }
}

The result but bug in time

getting sql error unknown column in where clause when trying to filter data

In the SQL query where city clause when I put string ‘delhi’ I get results but when I put a variable like below I get error unknown column delhi in where clause. how to solve the issue?

router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  const singleQuoteLocation = location.replace(/"/g, "'");
  connection.query(
    `select * from weather_data where city=${singleQuoteLocation}`,
    (err, results, field) => {
      if (err) {
        console.log(err);
      } else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});

When should I use functions as classes in Javascript?

I wish to create two sets of information that I’m going to re-use, one for a beer and one for a dispenser of beer, in Javascript.

The information is retrieved from an API, and all the beers are objects with an ID, name etc.

I’m wondering if I should bother with making each beer into a function like this:

function Beer() {
   this.Id = 0;
   this.Name = "";
   
   etc.
}

and then instantiate by setting a variable to a new Beer() through a forEach loop on the parsed JSON string. Is it worth it? Or should I just take the information directly from the API every time I reference different information about each beer? In other words, if this is not the time to use functions as pseudo-classes, when is?

If it helps, I’m writing in MVC, so I’m planning on having the information about the beer and the dispenser in my model, so I can use it with the controller and display it in my view very easily.

Function call from js script in ejs file tags

Suppose an ejs file for upvoting system:

<% if(clicked(post_id)==1) %>
    // load green button 
<%} else {%>
     // load red button

 <script>
 function clicked(id){
   if(currentUser.upvotes_downvotes===undefined)
       return -1;
   PreClicked = arr.find(clicked => {
        return clicked.postId.equals(id);})
   if(PreClicked === undefined)
    return 0;
   else if(PreClicked.type === "upvote")
     return 1;
   else if(PreClicked.type === "downvote")
     return 2;
     }
   </script>

But I am getting clicked is not defined

Passing array from tickboxes to a button- Jquery

So, I am trying to make id of each row into array and when the checked boxes are ticked, a button will show. From this button, we can have all the selected checkboxes id.
Notes: the checkboxes id actually likes this :

<input type="checkbox" id="chkT{$rows.id}" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

This is because, each row is getting it’s data from database, hence the {$rows.id}.
In the snippet, i delete the {$rows.id} just for example.

  1. the console.log is used for me to check whether the id is in array or not.
  2. I have tried the following codes regarding arrays, but the id’s are not in array.
let ids=[]
$(document).ready(function(){
    $('.js-checkbox').change (function() {
        if ($(this).attr('id') === 'chkAll'){
            if ($(this).prop('checked') === true){
                $('.single-row-checkbox').prop('checked', true);
                //ids.push($(this).attr("id")); 
                ids.push('.single-row-checkbox'.id);
                $('#conditional-part').show();
            }else if ($(this).prop('checked') === false){
                $('.single-row-checkbox').prop('checked', false);
                ids.pop($(this).attr("id"));
                //ids.pop(this.id);
                $('#conditional-part').hide();
            }
        } else if ($(this).attr('id') === 'chkT'){
            const checked = $('.single-row-checkbox');
                if (checked.length >= 2) {
                    $('#conditional-part').show();
                    //ids.push(this.id);
                    ids.push($(this).attr("id"));   
                } else {
                    $('#conditional-part').hide();
                    ids.pop($(this).attr("id"));
                }

        }
    });
});


I have achieve to make the selected checkbox into array using this code :

    let arr= [];
    function toggleTick_Change(){   
        var arr = $.map($('.single-row-checkbox:checkbox:checked'),     function(e, i) {
            return +e.value;
        });
        console.log('the checked values are: ' + arr.join(','));
        $('#conditional-part').show();
      
      //bind the event handler to it
          $arr.on('click', function(){
            btnPrintCNT_Click();
        });
    }

    function btnPrintCNT_Click(id){
        console.log('the checked values are: ' + id);   
    }
 #conditional-part{
    display:none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<span id="conditional-part" >
      <div class="input-group "  role="group" aria-label="..." style="width: 85px; margin-top: 2px; " >
                <span class="input-group-btn">
                        <button id="btnPrintCNT" type="button" class="btn btn-sm btn-primary" style="margin: 2px; width: 100px; margin-left: 20px; float: left;"                        onclick="javascript:btnPrintCNT_Click()">CNT</button>
                </span>
            </div>
    </span>
                
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="single-row-checkbox" onchange="toggleTick_Change()" />
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

But now, problem I faced are:

  1. How to call the id in array from ticked checkboxes to the button?
  2. How do I ticked all checkboxes without ticking it one by one?

Any help is highly appreciated. Thank you.

Angular – Apply decimal pipe to an input

I want to apply decimal pipe on an input so the user can see comma separated numbers as he/she types. I have tried the ngx-mask but that only works if you type in the input. When you patch a value to the input it doesn’t transform the value into decimal format.

Como puedo agregar objetos a un mismo item de LocalStorage?

Estoy empezando en JavaScript, tengo en mente crear una pagina de ventas, primero lo haré con local storage antes de meterme con bases de datos. creo que si puedo resolver esto podré hacer lo demás sin problema. Este script es solo para cuando haga el registro de los usuarios en la pagina, pero se guarda la misma información. Ya he intentado de muchas maneras, mi ultima opción ha sido preguntar.

CODIGO-JAVASCRIPT

const users = [], allUsers = []; // CREO LAS LISTAS DE LOS USUARIOS

// CLASE PARA GUARDAR LA INFORMACION DE LOS USUARIOS
class Users {
    constructor(id, nombre, edad, peso) {
        this.id = id;
        this.nombre = nombre;
        this.edad = edad;
        this.peso = peso;
    }
}

// SE PIDEN LOS DATOS DE CADA USUARIO
const id = getRandom();
const nombre = prompt('Nombre del nuevo usuario');
const edad = parseInt(prompt('Edad del nuevo usuario'));
const peso = prompt('Peso del nuevo usuario');
users.push(new Users(id, nombre, edad, peso));

// PREGUNTA SI EXISTE EL ITEM CON LA CLAVE EN EL LOCAL STORAGE
let existingUsers = JSON.parse(localStorage.getItem('allUsers'));
if (existingUsers == null) {
    localStorage.setItem('allUsers', allUsers);
}

// INTENTA ALMACENAR CADA USUARIO EN EL ITEM ALLUSERS DEL LOCAL STORAGE
localStorage.setItem('users', JSON.stringify(users));
allUsers.push(users[0]);
localStorage.setItem('allUsers', JSON.stringify(allUsers))

// ESCRIBE EN EL DOCUMENTO LA INFO DEL USUARIO REGISTRADO
console.log(`ID: ${id}<br>
Nombre: ${nombre}<br>
Edad: ${edad}<br>
Peso: ${peso}<br>`);

// FUNCION QUE DEVUELVE UN NUMERO ALEATORIO GRANDE PARA EL ID
function getRandom() {
    const max = 100000000000, min = 999999999999;
    const id_aleatorio = Math.round(Math.random() * (max - min ) + min);
    return id_aleatorio;
}