Javascript: Input the duration of movie and return number of hours

I’m new to react and as practise, I’m building a react app. The form has a duration input which expects the data either in minutes or hours eg. 132m or 2.5h. The function should return the number of hours based on the input or show error in alert that “Duration is in invalid format”.

How can I go about this? The value is string and so I was thinking of using duration.includes('m') or duration.includes('h') but the problem is it will accept “1h32” for example. I also want to know how float can be extracted from the string?

image not appear in pdf – html2pdf

My Image tag:

 <img src="http://codeskulptor-demos.commondatastorage.googleapis.com/GalaxyInvaders/back07.jpg"/>

And my html2pdf code:

 html2pdf(this.$refs.document, {
          margin: 0.2,
          filename: "invoice.pdf",
          pagebreak: { after: ".sautDePage" },
          image: {
            type: "jpeg",
            quality: 0.98,
          },
          html2canvas: {
            scale: 1,
          },
          jsPDF: {
            unit: "in",
            format: "letter",
            orientation: "portrait",
          },
        });

Please give me any idea because now my image not display inside pdf. It is visible on page but not in pdf.

SwiperJS – padding on wrapper

would like to set padding on my slider wrapper, when i do it manually, for example I set padding-left:15px; on wrapper or any parent div, the last slide is not showing properly, in fact 15 pixels are hidden by the overflow..

I am using swiper-bundle.6.5

The html rendered:

<div class="swiper-container swiper-container-initialized swiper-container-horizontal swiper-container-rtl swiper-container-android px-3">
    <div class="swiper-wrapper" id="swiper-wrapper-44269aed36ad10c2c" aria-live="polite" style="transform: translate3d(330px, 0px, 0px); transition-duration: 0ms;">
        <div class="swiper-slide" style="width: 210px; margin-left: 10px;" role="group" aria-label="1 / 3">
            mySlide1
        </div>
        <div class="swiper-slide swiper-slide-prev" style="width: 210px; margin-left: 10px;" role="group" aria-label="2 / 3">
            mySlide2
        </div>
        <div class="swiper-slide swiper-slide-active" style="width: 210px; margin-left: 10px;" role="group" aria-label="3 / 3">
            mySlide3
        </div>
    </div>
</div>

The js :

new SwipeLoader(_swiper_target, {
    debugger: true,
    direction: 'horizontal',
    pagination: {
        el: '.' + unique_id + ' .swiper-pagination',
        clickable: true
    },
    navigation: {
        nextEl: '.' + unique_id + ' .swiper-button-next',
        prevEl: '.' + unique_id + ' .swiper-button-prev'
    },
    slidesPerView: 1.5,
    spaceBetween: 10,
    breakpoints: {
        320: {
            slidesPerView: 1.5,
            spaceBetween: 10
        },
        480: {
            slidesPerView: 1.5,
            spaceBetween: 10
        },
        640: {
            slidesPerView: 1.5,
            spaceBetween: 10
        },
        800: {
            slidesPerView: 3,
            spaceBetween: 10
        }
    }
});

Thanks

Reload a div on webhook response

I’m writing code in express.js. Here I want to reload a div on the webhook response.

Here is a sample piece of my code.

server.js

router.post("/reviews", async (req, res) => {
  console.log(req.body.review.comments); 
});

This block triggers perfectly whenever there is an action happening at my webhook.
I use the below HTML to post the data and whenever there is a response, I want to refresh it(Getting data on refresh is handled and is working fine, tested this when I am posting data).

sample.html

<div id="reviewsWrapper">
 <div class="reviewsContainer" id="reviewsContainer">
  New Review Received
 </div>
</div>

<script>
    var mainForm = document.querySelector('#form');
    mainForm.addEventListener("submit", handleFormSubmit);

    async function handleFormSubmit(event) {
        event.preventDefault();
        const form = event.currentTarget;
        const url = form.action;
        try {
            const formData = new FormData(form);
            const data = JSON.stringify(Object.fromEntries(formData));

            const config = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: data,
            };

            const rawResponse = await fetch(url, config);
            const content = await rawResponse.json();
            if (content)
                $('#reviewsWrapper').load(location.href + ' #reviewsWrapper>*')
        } catch (error) {
            console.error(error);
        }
    }

</script>

I want to understand, whenever I have a new action in my webhook, how can I refresh my div(reviewsWrapper)?

Thanks

How to get a value from color picker in Javascript

When the user chose a colour in the colour picker.
How can I get the colour value and output in the console?
The color is as

<!DOCTYPE HTML>
<HTML>

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
</head>
<body>
<label for="color">Please chose a color </label>
<input type="color" id="color" name="color2">

 <script>
        let userColor= document.querySelector("#color").value
        console.log(userColor)
 </script>
 </body>
</html>

Laravel AJAX create HTML DOM(tooltip) element onhover

How to create dynamically tooltip using AJAX in Laravel?

I’ve got table, each element of table has it own ID, stored in <div id="[numbers]" hover="tooltip(this.id);"></div>

For each element I want to “create” or display tooltip(for displaying data like name, date, etc.).

Is it possible? This is what I’ve got at the moment:

 // blade.view
        function test(id)
        {
            $.ajax({{ 
                type: "GET",
                url: "{{ route('box.getData') }}",
                success: function(data){
                    alert("working");
                }
             }});
        }

Route:

Route::get('/box', 'AppHttpControllersBoxController@getData')->name('box.getData');

How to proceed with that in Controller?

Making dynamic react select component, not getting desired results,

I want to render a dynamic select/dropdown which I will fetch from an api as a template, I’m trying to pass on dynamic data to react select statement, still not getting exact response.
I want to display n number of dropdown, which be received from an api. Label of the dropdown will server as a question and options will be the answers.
Can someone help me figure out what shall be correct approach.
Below is my functional component for the same.
Thanks!

export const SurveyDropdown = () => {
  const [selectedSurvey, setselectedSurvey] = useState(); //default value

  function handleSelectChange(event) {
    setselectedSurvey(event.target.value);
  }
  console.log(selectedSurvey)
  const surveyData = [
    {
      id: 1,
      surveyQuestion: "Question One",
      type: "dropdown",
      option: ["optionOne", "optionTwo", "optionThree"],
    },
    {
      id: 2,
      surveyQuestion: "Question Two",
      type: "dropdown",
      option: ["optionOne", "optionTwo", "optionThree"],
    },
    {
      id: 3,
      surveyQuestion: "Question Three",
      type: "button",
      option: ["optionOne", "optionTwo", "optionThree"],
    },
  ];

  let optionTemplate = surveyData.map(surveyData => (
    <option value={surveyData.option} key={surveyData.surveyQuestion}>{surveyData.option.values}</option>
  ));

  console.log(optionTemplate);

  return (
    <>
      <FloatingLabel
        controlId="floatingSelect"
        label="This is question"
        value={selectedSurvey}
        onChange={handleSelectChange}
      >
        <Form.Select aria-label="Floating label select example">
          <option>{optionTemplate}</option>
        </Form.Select>
      </FloatingLabel>
    </>
  );
};

custom component argument not passed

I am currently familiarizing myself with the concept of web components.

I am trying to give the custom component a stylesheet, so that it can mimic the page content. But the argument I am trying to pass seems to be ‘null’.

What I would expect to happen is:

  1. The component-style argument is succesfully received
  2. As a result, the webcomponent loads the intended stylesheet.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web Component Test</title>
    <script src="DiceComponent.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p>if it works, you shall see a webcomponent below. </p>
<p>if the webcomponent manages to use the same style as the page, it should turn green!</p>
<my-diceroll component-style="style.css"></my-diceroll>

</body>
</html>

DiceComponent.js

class DiceRoll extends HTMLElement {

    constructor() {
        super();
        const shadow = this.attachShadow({mode:'open'});
        let paragraph = document.createElement("p");
        paragraph.id = "dice-text";
        paragraph.textContent = "GREEN when argument is passed, RED when not";
        console.log(paragraph.id);

        //style stuff
        const style = document.createElement('link');
        style.setAttribute('rel','stylesheet')
        style.href = this.hasAttribute('component-style') ? this.getAttribute('component-style') : 'ComponentStyle.css';

        shadow.append(paragraph);
        shadow.append(style);
    }
}

window.customElements.define('my-diceroll', DiceRoll);

style.css

p {
    color: green;
}

ComponentStyle.css

p {
    color: red;
}

current result from (chrome) browser:

browser-result

p tag is removing new line character in string

I have a string that contains a new line character. For example:

const myString = `hellonstring`

I am then trying to diaply this string in a functional component, which is wrapped around a p tag. For example:

export default function App() {
  const testString = "hinString";
  return (
    <div className="App">
      <p>{testString}</p>
    </div>
  );
}

For some reason, the p tag simply displays “hello string” on one line when I’d like for it to be displayed across two lines. Is there a way that I can stop the p tag from removing the new-line character from within the string?

The following Code Sandbox contains the executable example: https://codesandbox.io/s/unruffled-allen-ehrsd8?file=/src/App.js

How to scroll all content in block with position sticky and top styles?

As you can see header always is fixed and has position: fixed, siderbar has property top: 6rem and also styles for scrolling, but content doesn’t scroll fully. How I fix it without changing header styles? I would like to stay the same what you see when run this snippet but with correct scroll.

* {
  margin: 0;
  padding: 0;
}

.container {
  position: relative;
  height: 1000rem;
}

.header {
  width: 100%;
  background: #000;
  display: flex;
  font-size: 4rem;
  color: #fff;
  z-index: 2;
  position: fixed;
  top: 0;
}

.sidebar-title {
  background: #999;
  width: 100%;
}

.sidebar {
  background: #f20;
  width: 20%;
  z-index: 1;
  top: 6rem;
  position: sticky;
  height: 100%;
  overflow-y: scroll;
  max-height: 100vh;  
}
<div class="container">
  <header class="header">header</header>
  
  <div class="sidebar">
    <div class="sidebar-title">SIDEBAR</div>
    <ul>
      <li>aaaaaaaaaaaaaaaa</li>
      <li>bbbbbbbbbbbbbbbb</li>
      <li>ccccccccccccccc</li>
      <li>dddddddddddddd</li>
      <li>eeeeeeeeeeeee</li>
      <li>fffffffffffffffffff</li>
      <li>ggggggggggggg</li>
      <li>hhhhhhhhhhh</li>
      <li>iiiiiiiiiiiiiiiii</li>
      <li>jjjjjjjjjjjjjj</li>
      <li>kkkkkkkkkkk</li>
      <li>llllllllllll</li>
      <li>mmmmmmmmmmmmm</li>
      <li>nnnnnnnnnnnnnnn</li>
      <li>oooooooooooooo</li>
      <li>pppppppppppp</li>
      <li>qqqqqqqqqqqqqqq</li>
      <li>rrrrrrrrrrrrrrr</li>
      <li>ssssssssss</li>
      <li>tttttttttttt</li>
      <li>1111</li>
      <li>2222</li>
      <li>3333</li>
      <li>4444</li>
      <li>5555</li>
      
    </ul>
  </div>
</div>

How to validate form Dynamically added?

I have a form which adds a line dynamically when click on add form.

<form class="address">
  <input type="text" class="add_name">
  <input type="test" class="add_zip">
</form>

When Clicked on lets say a button add address:

<form class="address">
  <input type="text" class="add_name">
  <input type="test" class="add_zip">
    //added line when clicked on btn
  <input type="text" class="add_name">
  <input type="test" class="add_zip">
</form>

I used following code

 $('.address').each(function(){
    var address_form = $($this);
    if(address_form.find('add_name').val() == ''){
       //dosomething
     }else{
        console.log($form.find('add_name').val());
     }
 });

lets say if I put both address only first address is shown and second one undefined.

WHAT is JSX syntax reactjs

I’m fresher and I want to learn about JSX syntax reactjs for my java interview if anyone knows kindly explain and give some examples about it.

Want to know about JSX syntax reactj

MongooseError: Query was already executed: Users.find({ username: ‘b’ })

export const getFollowers = async (req,res) => {
                console.log(req.body)
                const profilename=req.body.profilename
                const followingarray = []
              
                try{
             await userModel.find({username:profilename},async (err,data)=> {
                const following = data[0].following
         
              
                following.map(async(whoimFollowing)=>{
                  
                await userModel.find({username:whoimFollowing},async (err,whoimFollowingdata)=> {
                       console.log(whoimFollowingdata) 
                       followingarray.push(whoimFollowingdata)
                    
                    })
        
                })
           
             }).then((res)=> {
           
             })
                }catch(e){
                   
                }
            }

im getting the error:
this issue happened when i added await to the UserModel.find function because im trying to add data i find from it into an array without the await would cause me problems

     const err = new MongooseError('Query was already executed: ' + str);
                  ^

MongooseError: Query was already executed: Users.find({ username: 'b' })
    at model.Query._wrappedThunk [as _find] (C:Portfolio ProjectsActual socialmediaAppServernode_modulesmongooselibhelpersquerywrapThunk.js:21:19)
    at C:Portfolio ProjectsActual socialmediaAppServernode_moduleskareemindex.js:372:33
    at processTicksAndRejections (node:internal/process/task_queues:78:11) {
  originalStack: 'Errorn' +
    '    at model.Query._wrappedThunk [as _find] (C:\Portfolio Projects\Actual socialmediaApp\Server\node_modules\mongoose\lib\helpers\query\wrapThunk.js:25:28)n' +
    '    at C:\Portfolio Projects\Actual socialmediaApp\Server\node_modules\kareem\index.js:372:33n' +
    '    at processTicksAndRejections (node:internal/process/task_queues:78:11)'
}