Ways to activate a different jQuery event by utilizing the output from a previously run jQuery event

I have a button on my website that looks like this:

<a id="btn" class="button">Click Me!</a>

When this button is clicked, it triggers a jQuery function as shown below:

$("#btn").on("click", function() {
  $.ajax({
    url: 'index.php',
    type: 'post',
    data: {product_id: 1, qty: 2},
    dataType: 'json',
    success: function(json) {
       if (json['success']) {
          console.log('Product added to cart');
       }
       if (json['error']) {
          console.log('Product not added to cart');
       }
    });
});

Now, I am wondering if it is possible to trigger another jQuery event after the above function is executed without modifying the existing code. The new function would use the return values of the previous function, like so:

function anotherAction(json_array) {
    if (json_array['success']){
        // Perform another action here
    }
}

Answer №1

Are you saying

function anotherAction() {
  if (submitBtn() == 'Submitted'){
    console.log('Button is submitted');
  }
}

However, you must ensure that str has a global scope

Maybe something like this

let str;
$("#btn").on("click", function() {
  str = 'Submitted';
});

$("#check").on("click", anotherAction);

function anotherAction() {
  console.log('Button has '+(str === 'Submitted' ? "" : "not ")+'been clicked');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn" type="button">Click</button>

<button id="check" type="button">Check</button>

Answer №2

There is no way to modify the function mentioned above.

Unfortunately, it is not possible to do so. The return value of the `submitBtn` function is not utilized or stored within the click event for `"#btn"`. Therefore, the returned value will remain unknown.

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

Switch out either even or odd divs within a container

I need help figuring out how to alternate the background colors of divs within a container. I want the first one to have a red background, the second to have blue, the third red again, and so on... Here is the code I currently have: <div>...</di ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

Having trouble getting a constructor to function properly when passing a parameter in

Here's the code snippet I'm working with: import {Component, OnInit} from '@angular/core'; import {FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase} from 'angularfire2/database-deprecated'; import {Item} ...

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

The functions getFiles and getFolders will consistently retrieve a single file or folder each time they are

When attempting to fetch all files and folders from my Google Drive, the function .getFiles() is only returning one file, while .getFolders() is only returning a single folder. However, I can confirm that there are multiple folders and files in my drive. ...

Exploring the DOM with jQuery to effectively select multiple elements

I am currently attempting to locate and select all elements with the "findme" class, and then identify the selects that are located nearby. http://jsfiddle.net/R93md/1/ Specifically, I have experimented with $(".findme").parent().prev().first(); Once ...

Refreshing an HTML table with new data using jQuery and Ajax after a different selection

Currently, I have a piece of code that allows me to select two players and display some statistics about them. The data is presented using a regular table (image1). The issue I am facing is that when I select a new player, instead of updating the informat ...

javascript - substitute the dash (hyphen) with a blank space

For quite some time now, I've been on the lookout for a solution that can transform a dash (hyphen) into a space. Surprisingly, despite finding numerous responses for changing a space into a dash, there seems to be a scarcity of information going in t ...

How to prevent selection of specific months in Bootstrap datepicker

I've been attempting to disable specific months in a datepicker using the datesDisabled option. Even though the documentation states that it should work by passing an array of strings, I haven't been able to make it function properly. Here' ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

In VueJS, the v-for directive allows you to access both parameters and the event object within

Imagine having nested elements that repeat using v-for in the following structure: <div id="container"> <div v-for="i in 3"> <div v-for="j in 3" v-on:click="clicked(i,j)"> {{i+&a ...

An issue with jQuery and LESS causing stylesheets to update only once

Struggling with updating a custom CSS href - everything works perfectly the first time, but subsequent updates do not reflect any changes on the page. Even though I can see the href updating in Chrome debugger and there are no errors being thrown by LESS, ...

Styling Result received from Web API call within an array

I am currently working on a function call that retrieves the result of an SQL query in an array format. app.get('/alluser', (req, res) => { console.log("All Users") user.getAllUsers(function (err, result) { if (!err) ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Steps for styling an AngularJS Popup:1. Determine the desired appearance for

I have some code that displays a popup when clicked, along with its automatically generated CSS. I want to be able to make changes to the CSS by adding IDs or classes to it. How can I assign IDs or classes to this element so that I can easily target them f ...

Utilizing Node.js ORM2 callback functions with custom parameters

Currently, I am developing models using a for loop: for (var j = 0; j < data.length; j++) { models.MyModel1.create({ name : data[j].name }, function(err, model){ if (err) { throw err } ...