How should you go about including an optional parameter in a function that currently only has one parameter?

I have a function that I need to use in an onClick action as well as other parts of the code. I am attempting to create an optional parameter that returns a class object instead of a false value.

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
  .html('Click me') // Try edit it...
  .on('click', test)

Output:

{
originalEvent:[object PointerEvent],
type:"click",
isDefaultPrevented:f returnFalse {...},
target:<button class="btn btn-warning m-auto"></button>,
currentTarget:<button class="btn btn-warning m-auto"></button>,
relatedTarget:null,
timeStamp:2798.800000000745,
jQuery36007002776368131782:true,
delegateTarget:<button class="btn btn-warning m-auto"></button>,
handleObj: {...},
data:undefined
}

Answer №1

The issue arises when passing the function directly to jQuery#on(), causing it to receive all arguments passed by on.

It's equivalent to:

//             vvvvvvv----------vvvvvvv--- Capture all arguments passed by `on` and pass them to `test`
.on('click', (...args) => test(...args))

Furthermore, since jQuery#on() passes an argument to your function, namely the event object, it will not revert to using the default value.

To overcome this, you can create an anonymous wrapper around your function that does not forward the arguments to test:

import $ from 'jquery'
const test = (optionalParam=false) => {
console.log(optionalParam)
console.log("hey")
}
$('button')
  .html('Click me')
  //                       vv--- Do not pass any arguments here
  .on('click', () => test())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we rearrange the positions of three items in an array?

I am dealing with a function that returns an array of objects structured like this const allGreen = _.filter( sidebarLinks, side => !isServicePage(side.slug.current) ); https://i.stack.imgur.com/dR8FL.png I am attempting to rearrange the positions of ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...

The JSON file containing API data is stored within the _next folder, making it easily accessible to anyone without the need for security measures or a login in the Next

When accessing the protected user Listing page, we utilize SSR to call the api and retrieve all user records which are then rendered. However, if one were to check the Network tab in Chrome or Firefox, a JSON file containing all user data is generated and ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

JQuery ajax DELETE request encounters issues during the OPTIONS stage

I'm encountering an issue while trying to send a delete request using JQuery as it consistently results in a 500 internal server error. Here's the code snippet I'm using for the request: $('#deleteReview').click(function(event, ui ...

Prevent the date each month in asp.net

Is there a way to block Sundays for all months and years in a text box with the Text mode set to Date? <asp:TextBox ID="txtfromdate" runat="server" Enabled="True" OnTextChanged="From_TextChanged" TextMode="Date" ></asp:TextBox> ...

Sending an object as a prop in React component

I have a function class: function TopicBox({topicName, article1}) { return ( <div className="TopicBox"> <h1>{topicName}</h1> <div className="topicDivider" /> <Ar ...

Error Connecting to Database with Node.JS MySQL Module - ECONNRESET Issue

Attempting to establish a connection with my database using the mysql module has been quite the challenge. Each time I try, an error seems to pop up: read eCONNRESET There is problem. (The final part is from my console log, as seen below.) I've ruled ...

Disable the outer div scrolling in VueJS, but re-enable it once the inner div has reached the bottom of

I am currently working on a webpage that contains multiple divs stacked vertically. Here is the concept I am working with: Once the scrollbar reaches the bottom of the first div, the outer scrollbar will be disabled and the inner scrollbar will be enabled ...

Combining objects using ES6 import/export with async/await functionality

I am facing a situation where I have two files named config.js and config.json and my goal is to combine them into one object and then export it: config.json { "c": 3 } config.js import fs from "fs"; import fse from "fs-extra& ...

Executing a js.erb template while submitting a form with AJAX in a Rails application

My form setup looks like this: <div class= "parent-container"> <%= form_with scope: @company, url: companies_path, html: { class: "form-inline", remote: true, "data-type" => :js, id: "new-company-create" }, local: true do |f| %> <d ...

Utilize CSS styling on dynamically loaded HTML content

I am working on a project similar to the StackOverflow editor. I am fetching markdown text, converting it to HTML, and then displaying it in a preview area. However, when I try to style the injected HTML elements using CSS, the styles are being ignored. Up ...

Prevent the parent component's ripple effect from being activated by the child component

If I have a simple code snippet like the following: <ListItem button={true} > <Typography variant='caption' color='primary'> {value} </Typography> <Button onClick={foo} > Button ...

Search for documents using jQuery on the page

Here is the layout of a page: HTML <div class="alert alert-dismissable"> <div class="form-group text-center"> <div id="Section"> <div class="row"> <div class="col-md-12"> ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

Determining a User's Connection Status in ReactJS: Cellular Network or WiFi?

Are there any tools or applications available that can determine if a user is connected to WiFi or using a cellular network? ...

Bringing JQuery into your Electron project through HTML

Working on some ElectronJS HTML coding and in need of using JQuery within the HTML. I've gone ahead and installed jQuery with npm install jquery. The question is, which file do I import to make use of JQuery? <!DOCTYPE html> <html lang="en" ...

What is the best way to break down this function from props in React?

Forgive me if this question sounds naive, but as I delve into the world of React and useState, I am encountering a scenario where I have a signup function coded. Upon sending a username and password through a POST request to an API endpoint, a response mes ...

Need to create a callback within a sequence of events?

Is it possible to create a callback chain like this? Widget.update(...).onUpdate(function(data){ console.log('updated'); }); Here is the current code snippet: var Gateway = {}; Gateway.put = function(url, data, callback) { $.ajax({ ...