How to print a function using a click event

I am doing the Print all even numbers from 0 – 10 challange, I created a funciton that should take a usuers input and give the even number of it, if it’s 10, 100, 1000, 10 000 etc.

 <form id="form">
   <input class="input" type="text">
   <input class="submit" type="submit">
 </form>

 <div class="output">
   <p>Output</p>
   <div class="outcome"></div>
 </div>
//Empty Array
arrayEvenNum = []

/function that loops through input value and push to array
function loopInput(){
    let userInput = document.querySelector(".input").value

    for (let i = 0; i <= userInput; i+=2) {
       arrayEvenNum.push(i)
    }

}

let submit = document.querySelector(".submit")

submit.addEventListener("click",() => {
    //print numbers in array in HTML

})

Setting a specific parameter in JavaScript

I have a function that takes multiple parameters where I give each parameter a default value. When I call this function I only want to change a specific parameter. Is this possible to do in JavaScript? I was unable to find a clear answer in a Google search.

I understand that I can use several ‘if’ statements within my function however I am able to solve this problem in Python through the example:

setValues(val2="new")

This does not work in JavaScript being that the assignment occurs to the first positional variable in the function rather than the one explicitly chosen.

I have the code:

function setValues(val1="a", val2="b", val3="c")
{
  /*
    Print the value of each variable. 
  */
}
  
setValues(val2="new");

Output:

val1 = "new"
val2 = "b"
val2 = "c"

Expected:

val1 = "a"
val2 = "new"
val3 - "c"

Vanilla Js – how to show specific image of a slider based on clicked item in previous page

//JS page one
    let box = document.getElementsByClassName("box");

    //click event
    box[0].addEventListener("click", fn1);
    box[1].addEventListener("click", fn2);
    box[2].addEventListener("click", fn3);
    box[3].addEventListener("click", fn4);

  //show description at click and hide "click for info"
    function fn1() {
    window.location = 'carousel.html';
    }
    function fn2() {
    window.location = 'carousel.html#2';
    }
    function fn3() {
    window.location = 'carousel.html';
    }
    function fn4() {
    window.location = 'carousel.html';
    }
    
   //JS page two
      /*lightbox code*/ 
      let slideIndex = 1;
      showSlides(slideIndex);
      
      // Next/previous controls
      function plusSlides(n) {
        showSlides(slideIndex += n);
      }
      
      // Thumbnail image controls
      function currentSlide(n) {
        showSlides(slideIndex = n);
      }
      
      function showSlides(n) {
        let i;
        let slides = document.getElementsByClassName("mySlides");
        if (n > slides.length) {slideIndex = 1}
        if (n < 1) {slideIndex = slides.length}
        for (i = 0; i < slides.length; i++) {
          slides[i].style.display = "none";
        }
        slides[slideIndex-1].style.display = "block";
      }
<!--HTML PAGE ONE-->
    <div id="container">
      <!--one-->
      <div class="box">
        <img title="paint one" class="image" src="images/paintings/1.jpg"> 
        <p class="showText"></p>
      </div>
     <!--two-->
      <div class="box">
        <img title="paint two" class="image" src="images/paintings/2.jpg"> 
        <p class="showText"></p>
      </div>
      <!--three-->
      <div class="box">
        <img title="paint one" class="image" src="images/paintings/3.jpg"> 
       <p class="showText"></p>
      </div>
     <!--four-->
      <div class="box">
        <img title="paint two" class="image" src="images/paintings/4.jpg"> 
        <p class="showText"></p>
      </div>
    </div>
    
     <!--HTML PAGE 2 - CAROUSEL-->
    <div id="lightbox">
    <div class="slideshow-container">

  <!-- Full-width images with number and caption text -->
  <div class="mySlides fade">
    <div class="numbertext">1 / 4</div>
    <img class="image" src="images/paintings/1.jpg">
    <div class="text">Caption Text</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 4</div>
    <img class="image" src="images/paintings/2.jpg">
    <div class="text">Caption Two</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 4</div>
    <img class="image" src="images/paintings/3.jpg">
    <div class="text">Caption Three</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">4 / 4</div>
    <img class="image" src="images/paintings/4.jpg">
    <div class="text">Caption Three</div>
  </div>
  <!-- Next and previous buttons -->
  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>
  </div>
   </div>

I was wondering if it is possible to show the desired image in page 2 Html based on what is clicked in page 1 Html. I know a solution could be to create an HTML page for each photo I want to show on click: I should just change the windows.location of the addEventListener and then in the JS file set the number corresponding to the slideIndex but it would be really good to find a solution without duplicating the pages. I hope I was clear

Remove Duplicates from Json Object

{ All Products /// Linternas /// Linternas Antichispas: 6 All Products /// Linternas /// Linternas LED: 14 All Products /// Linternas /// Linternas LED UV: 2 All Products /// Linternas /// Linternas LED de Cabeza: 8 All Products /// Linternas /// Linternas LED de Emergencia: 9 All Products /// Linternas /// Linternas LED de Inspección: 8 All Products /// Linternas /// Linternas Tácticas: 4 All Products /// Linternas /// Linternas-Baterías y Accesorios: 4 All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas: 1 All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas Recargables: 3 All Products /// Linternas /// Lámparas LED de Trabajo: 5 } [[Prototype]]: Object

the above mentioned is json object. i need to remove the duplicates.

Example :

All Products /// Linternas /// Linternas-Baterías y Accesorios -> this complete category is come under another level category .

All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas: 1

All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas Recargables: 3

Hence it is duplicated.
this duplicated category need to be removed All Products /// Linternas /// Linternas-Baterías y Accesorios

I need the result as

{ All Products /// Linternas /// Linternas Antichispas: 6 All Products /// Linternas /// Linternas LED: 14 All Products /// Linternas /// Linternas LED UV: 2 All Products /// Linternas /// Linternas LED de Cabeza: 8 All Products /// Linternas /// Linternas LED de Emergencia: 9 All Products /// Linternas /// Linternas LED de Inspección: 8 All Products /// Linternas /// Linternas Tácticas: 4 All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas: 1 All Products /// Linternas /// Linternas-Baterías y Accesorios /// Baterías / Pilas Recargables: 3 All Products /// Linternas /// Lámparas LED de Trabajo: 5 } [[Prototype]]: Object

Kindly guide me i need to work in javascript function

How to stop the rerender in videojs when the state update in react

I get the code from https://videojs.com/guides/react/.

If I update the state, my video rerender and the video start playing from first, how to solve.

Example code:

Videojs code:

import React from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

export const VideoJS = (props) => {
  const videoRef = React.useRef(null);
  const playerRef = React.useRef(null);
  const {options, onReady} = props;

  React.useEffect(() => {

    // Make sure Video.js player is only initialized once
    if (!playerRef.current) {
      // The Video.js player needs to be _inside_ the component el for React 18 Strict Mode. 
      const videoElement = document.createElement("video-js");

      videoElement.classList.add('vjs-big-play-centered');
      videoRef.current.appendChild(videoElement);

      const player = playerRef.current = videojs(videoElement, options, () => {
        videojs.log('player is ready');
        onReady && onReady(player);
      });

    // You could update an existing player in the `else` block here
    // on prop change, for example:
    } else {
      const player = playerRef.current;

      player.autoplay(options.autoplay);
      player.src(options.sources);
    }
  }, [options, videoRef]);

  // Dispose the Video.js player when the functional component unmounts
  React.useEffect(() => {
    const player = playerRef.current;

    return () => {
      if (player && !player.isDisposed()) {
        player.dispose();
        playerRef.current = null;
      }
    };
  }, [playerRef]);

  return (
    <div data-vjs-player>
      <div ref={videoRef} />
    </div>
  );
}

export default VideoJS;

App.js

import React from 'react';

// This imports the functional component from the previous sample.
import VideoJS from './VideoJS'

const App = () => {
  const playerRef = React.useRef(null);
  const [timestamp,setTimestamp]= useState(0) 
  const videoJsOptions = {
    autoplay: true,
    controls: true,
    responsive: true,
    fluid: true,
    sources: [{
      src: '/path/to/video.mp4',
      type: 'video/mp4'
    }]
  };

  const handlePlayerReady = (player) => {
    playerRef.current = player;

    // You can handle player events here, for example:
    player.on('waiting', () => {
      videojs.log('player is waiting');
    });

    player.on('dispose', () => {
      videojs.log('player will dispose');
    });

    player.on('timeupdate', function(){
    setTimestamp (player.currentTime()) 
   });
  };

  return (
    <>
      <div>Rest of app here</div>
      <VideoJS options={videoJsOptions} onReady={handlePlayerReady} />
      <div>Rest of app here</div>
    </>
  );
}

In the App.js, I update the timestamp in timeupdate listener, I get rerender and video again start playing from first.

Please help me to solve

Allow multiple markers in leaflet map rails 5

I need to allow users to place multiple markers, the max number of markers must be dynamic, the map is in a form, so when I send the form to the controller I have to get the latitude and longitude of the markers in an Array so I can processes them.

This is what I have for one marker:

  initialize: ->
    maps = $("*[data-mapanswer]")
    if maps.length > 0
      $.each maps, (index, map) ->
        App.MapAnswer.initializeMap map

    $(".js-toggle-map").on
      click: ->
        App.MapAnswer.toggleMap()

  initializeMap: (element) ->
    mapCenterLatitude        = $(element).data("map-center-latitude")
    mapCenterLongitude       = $(element).data("map-center-longitude")
    markerLatitude           = $(element).data("marker-latitude")
    markerLongitude          = $(element).data("marker-longitude")
    zoom                     = $(element).data("map-zoom")
    mapTilesProvider         = $(element).data("map-tiles-provider")
    mapAttribution           = $(element).data("map-tiles-provider-attribution")
    latitudeInputSelector    = $(element).data("latitude-input-selector")
    longitudeInputSelector   = $(element).data("longitude-input-selector")
    zoomInputSelector        = $(element).data("zoom-input-selector")
    removeMarkerSelector     = $(element).data("marker-remove-selector")
    editable                 = $(element).data("marker-editable")
    markerId                 = $(element).data("marker-id")
    answers                  = $(element).data("answers")
    marker                   = null
    markerIcon               = App.MapAnswer.createMarkerIcon(icon_related: false)
    markerRelatedIcon        = App.MapAnswer.createMarkerIcon(icon_related: true)

    createMarker = (latitude, longitude) ->
      markerLatLng  = new (L.LatLng)(latitude, longitude)
      marker  = L.marker(markerLatLng, { icon: markerIcon, draggable: editable })

      marker.addTo(map)
      return marker

    removeMarker = (e) ->
      e.preventDefault()
      if marker
        map.removeLayer(marker)
        marker = null
      $(latitudeInputSelector).val ""
      $(longitudeInputSelector).val ""
      $(zoomInputSelector).val ""
      return

    moveOrPlaceMarker = (e) ->
      if marker
        marker.setLatLng(e.latlng)
      else
        marker = createMarker(e.latlng.lat, e.latlng.lng)

      $(latitudeInputSelector).val(e.latlng.lat)
      $(longitudeInputSelector).val(e.latlng.lng)
      $(zoomInputSelector).val map.getZoom()
      return
    updateZoom = (e) ->
      $(zoomInputSelector).val map.getZoom()
      return

    if markerLatitude && markerLongitude
      mapCenterLatLng  = new (L.LatLng)(markerLatitude, markerLongitude)
    else
      mapCenterLatLng  = new (L.LatLng)(mapCenterLatitude, mapCenterLongitude)
    map              = L.map(element.id,{zoomControl: false}).setView(mapCenterLatLng, zoom)
    L.control.zoom({position: 'bottomright'}).addTo(map)
    L.tileLayer(mapTilesProvider, attribution: mapAttribution).addTo(map)

    if markerLatitude && markerLongitude
      marker  = createMarker(markerLatitude, markerLongitude)
    else if answers
      answers.forEach (answer) ->
        createMarker(answer[0], answer[1])

    if editable
      $(removeMarkerSelector).on "click", removeMarker
      map.on    "click",   moveOrPlaceMarker
      map.on    "zoomend", updateZoom


  createMarkerIcon: (marker_option) ->
    relatedIconClass = "map-icon-related" if marker_option.icon_related
    L.divIcon(
      className: "map-marker"
      iconSize:     [30, 30]
      iconAnchor:   [15, 40]
      html: "<div class='map-icon #{relatedIconClass}'></div>"
    )

I guess I have to modify createMarker but nothing is working

Unable to pass HTML data from client side to server side using google appscript

When the button is clicked, I want to capture the email ID and account name and pass this information to the server side.

The code works on the client side, but the server function does not fire, but it fails. I can see it under the execution log ad Failed.

I also tried using JSON stringify in the code. gs function, but doesn’t work either.

HTML

<script>

  

$('#btn').click(function () {

  console.log('Button is clicked');

          
            var accountId = $('select#accountData').val();
            console.log(accountId);
            var emailId = $('input#emailaddressId').val();
            console.log(emailId);

            var gaAccountData = {};

            gaAccountData.account = accountId
            gaAccountData.email = emailId
            console.log(gaAccountData);

            gaAccountData=JSON.stringify(gaAccountData)
            gaAccountData=JSON.parse(gaAccountData)
            google.script.run.onboardUsertoAccount(gaAccountData);
        });

</script>  


Code.gs

function onboardUsertoAccount(gaAccountData) {


    const Userdata = {
        "emailAddress": gaAccountData.email,
        "directRoles": [
            "predefinedRoles/viewer"
        ]
    }
    AnalyticsAdmin.Accounts.UserLinks.create(Userdata, gaAccountData.account, {
        "notifyNewUser": false
    });
}
                                        


how to hide secret keys in react js application (frontend side)

I am trying to hide a secret key in react js frontend application, I know it’s not a good idea, but I don’t have the choice, in fact I want my frontend application (react js) to be the only thing that send requets to my backend application and I thought it’s a good idea to have a secret key to send it in the backend side this way I’m sure that it a legitim request and allow it.

I tried .env it’s does’nt worded

Jest set TZ env variable PER test

I am running into an issue where I want to run some of my tests under different time zones.

After following a few links i found that you can set the TZ env var before calling jest in your package.json or command line like so:

{
  ...
  "test": "TZ=America/Sao_Paulo jest"
  ...
}

But this doesn’t scale properly say if i want to test both America/Sao_Paulo & Asia/Shanghai…I’d have to do something like this…

{
  ...
  "test": "TZ=America/Sao_Paulo jest & TZ=Asia/Shanghai jest"
  ...
}

I’ve also tried the approach with setting the timezone by manipulating process.env.TZ in beforeEach of each test BUT…it never actually picks up on the env when it goes runs my suites.

How to navigate to a new screen in react native using react navigation and the components are in a different file

I am planning to use React Navigation in my project to navigate within two screens.

The index.js looks like

<NavigationContainer>
  <Stack.Navigator initialRouteName="Home">
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Details" component={DetailsScreen} />
  </Stack.Navigator>
</NavigationContainer>

home.js contains a component called home and detailsScreen.js contains another component called detailsScreen.

  1. What should I do to navigate to detailsScreen from Home? Do I have to import/export anything? If yes, where? The official docs (https://reactnavigation.org/docs/navigating/) only consider the scenario where all components are in the same file.

  2. Can I call navigation.navigate in the following way?

return (
  <View>
    {navigation.navigate('Details')}
  </View>
)

I want to store an string with multi spaces in the function and after, I want to call that function from any loop that placed in the main function

From this program, I want to store an string with multi spaces in the function and after this, I want to call that function from while or do-while loop that placed in the main function in c language.
But it’s not working??

Here is my program in c that isn’t working correctly.

#include<stdio.h>

void print_full_name()

{

char name[100];

printf(“write your full name :”) ;

gets(name);

puts(name) ;

}

main()

{

int ch=1;

while(ch! =2) 

{

   printf("Enter 1 to continue and 2 for exit :");

   scanf("℅d", &ch) ;

   print_full_name() ;

}

}

If we remove the while loop from the main then this program is run without any error. But now with the loop any like while, do-while Or for this program is not run as expect.

Can please tell what is the error.

I tried many things that I changed all the loops in main function and I replace if condition with switch condition. Also tried other method to store string with spaces to replace gets() function like ℅[^n], fgets()etc many more but none of this working.

If anyone can help me to reach out from this problem so please..

Receivers Email (to) should change based on drop-down selection in ASP.NET

PROBLEM:

I am trying to solve a problem where there are 5 towers and each has respective recipients’ list.
When a particular tower is selected the form should auto-populate the respective email ids in the to textbox for user.

SOLUTION I TRIED:

  1. I tried to add a new method ‘Selection_Change’ to dropdown for tower which contains the email ids for each tower respectively.
 <asp:DropDownList ID="txtTowerValue" runat="server" SkinID="EmailTextbox" Font-Size="14px" Width="580px" Height="30px" BorderStyle="None">onselectedIndexchanged="Selection_Change"> 

 <asp:ListItem Value="--Please Select--">--Please Select--</asp:ListItem>
 <asp:ListItem Value="AO">AO</asp:ListItem>
 <asp:ListItem Value="MOD">MOD</asp:ListItem>
 <asp:ListItem Value="IO">IO</asp:ListItem>
 <asp:ListItem Value="SD">SD</asp:ListItem>
 <asp:ListItem Value="Security">Security</asp:ListItem>
 </asp:DropDownList></td>

Selection_Change method code:

protected void Selection_Change(Object sender, EventArgs e)
        {
            if (txtTowerValue.SelectedItem.Text == "AO")
            {
                txtNotifTo.Text = ConfigurationManager.AppSettings["ToAO"].ToString();
            }
            if (txtTowerValue.SelectedItem.Text == "IO")
            {
                txtNotifTo.Text = ConfigurationManager.AppSettings["ToIO"].ToString();
            }
            if (txtTowerValue.SelectedItem.Text == "MOD")
            {
                txtNotifTo.Text = ConfigurationManager.AppSettings["ToMOD"].ToString();
            }
            if (txtTowerValue.SelectedItem.Text == "SD")
            {
                txtNotifTo.Text = ConfigurationManager.AppSettings["ToSD"].ToString();
            }
            if (txtTowerValue.SelectedItem.Text == "Security")
            {
                txtNotifTo.Text = ConfigurationManager.AppSettings["ToSecurity"].ToString();
            }
        }

I also went through few suggestions which mentioned adding Autopostback=true for the drop-down but in that case the page reloads and the pop-up form closes down which is not helpful for my problem. I was hoping if anyone has any suggestions to tackle this problem using jQuery/Javascript or can give input on the code that I have put out here.

Thanks in advance!

Input type=”datetime-local” is accepting 6 digits for year selection allow 4 digits

Input type=”datetime-local” is accepting 6 digits for year selection allow only 4 digits for year selection.

<label for="date-start">Start Date</label>
                    <input class="date-picker" id="date-start">
                    <label for="end-date">End Date</label>
                    <input class="date-picker" id="date-end">

Expected: It should only 4 digits for year selection instead of 6 digits using html, bootstrap, jQuery, JavaScript

why Only last radio button control in list being set as checked?

<td>{{ $product->name ?? '' }}</td>
<td><img src="{{asset($product->image)}}" class="product-img-2" alt="product img"></td>
<td class="print-btn">
  <div class="form-check">
    <input class="form-check-input" value="active"  type="radio" name="status" id="flexRadioDefault1"
      {{ $product->status == 'active' ? 'checked' : '' }} >
    <label class="form-check-label" for="flexRadioDefault1">
      مفعل
    </label>
  </div>
  <div class="form-check-one">
    <input class="form-check-input" value="deactive"  type="radio" name="status" id="flexRadioDefault2"
      {{ $product->status == 'deactive' ? 'checked' : '' }}
    >
    <label class="form-check-label" for="flexRadioDefault2">
      غير مفعل
    </label>
  </div>