How can we prevent having an abundance of jQuery confirmation dialog boxes and instead focus on reusing them

I'm currently updating an old web application using jQuery.

Within the form, there are 40 buttons that trigger a confirmation prompt using javascript confirm. I aim to replace these with jquery modal dialogues.

While I've successfully implemented this for a few buttons, having to do it individually for all 40 seems tedious. The only variation between them is the javascript function called when 'Yes' is clicked.

Any ideas on how to streamline this process?

Sample code for button:

$("#confirm1dialogTitle").html("Approve?");
$("#confirm1dialogText").html("Do you want to approve this request?");
$('#confirm1dialog').dialog('open');

Inline script:

<script type="text/javascript">
$(function() {
    $("#confirm1dialog").dialog({
        bgiframe: true,
        autoOpen: false,
        width: 350,
        height: 350,
        modal: true,
        buttons: {
            'Yes': function() {
                window.document.forms[0].FDDStatus.value = "Approved";
                window.document.forms[0].DivisionApproval.value = "Yes";
                window.document.forms[0].setApprovalFields();
            },
            'No': function() {
                $(this).dialog('close');
            }
        }
    });
});
</script>

Inline HTML:

<div id="confirm1dialog" title="<span id='Title'>Title</span>">
   <div id="users-contain" class="ui-widget">
      <form>
         <span id="confirm1Text"></span>
      </form>
   </div>
</div>

Answer №1

If you want to consolidate the JavaScript that is constantly changing, you can encapsulate it in a function object for reuse.

For example, let's say your form looks like this:

<form><input id='btn1' /><input id='btn2' /></form>

You can create a helper function like this:

var confirmHelper = function(id, yesCallback) {
  $(id).click(function() {
    // Code from your example
    $("#confirm1dialog").dialog({
      bgiframe: true,
      autoOpen: false,
      width: 350,
      height: 350,
      modal: true,
      buttons: { 'Yes': yesCallback, 'No': function() { } }
    });
  });
};

Then you can apply this helper function to your buttons:

confirmHelper('btn1', function() {
  // Your previous callback code here
  window.document.forms[0].FDDStatus.value = "Approved";
  window.document.forms[0].DivisionApproval.value = "Yes";                                   
  window.document.forms[0].setApprovalFields();
});

confirmHelper('btn2', function() {
  // Your other JavaScript code here
});

This way, you can easily handle the functionality of all the buttons with ease!

Answer №2

In JavaScript, you have the capability to create 40 individual functions that will be triggered when the user clicks "yes" using only a single modal window.

Without knowing the specifics of your click() function, it is possible to incorporate a variable within it by utilizing attributes such as rel on the link being clicked or a specific class. By evaluating the value of this variable, you can determine which function needs to be executed accordingly.

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

Steps to verify multiple v-for loops and apply style if both are present

<div v-for="memberMembershipyear in memberMembershipyears"> <li v-for="membershipYear in membershipYears" :style="membershipYear.num === memberMembershipyear.num ? 'color:green' : color:red'"> {{membershipYear.me ...

Tips for sending an array from a higher-order component to a nested component in React Native using props

I have a scenario where I need to pass an array called "subjects" from the SubjectsScreen component to the MarkAttendanceScreen component and then display that array as a list using FlatList. Parent Component export default class SubjectsScreen extends C ...

What steps can be taken to display database results solely for the user currently logged in and created by them?

Currently, I'm in the midst of a project that involves extracting an HTML list from JSON data using JavaScript. The list is being displayed on the logged-in user's profile, showcasing job listings from the JSON data. While I've successfully ...

What is the method for sending arguments to material avatar using require?

import Avatar from '@material-ui/core/Avatar'; Here is an example of working code: <Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" /> However, I encountered ...

Avoid stretching the div to the edge of the screen

In the table on my page, I have implemented a feature using CSS to display additional information in a popup div. This works well when there is limited text, but if there is extensive text in the table, it extends beyond the screen width and becomes diffic ...

What might be causing the lack of JSON updates appearing on my webpage?

I am facing an issue with my JSON file. After making updates to the file, the changes are not reflected on my webpage. Even after refreshing multiple times, only the old data is being displayed. I am using xampp local server and ajax for retrieving the JSO ...

tips for integrating new features in protractor

Currently in our testing process we utilize protractor/selenium for test automation. I am eager to enhance certain functions, such as sendkeys and click, to not only log actions to the console but also increase reliability (we have observed that click fail ...

Using React Native, you can easily apply styles to View components by passing them

Is it a bug? Or is the View styles props object supporting inline props as well? For example, in the traditional way and also written in React Native documentation: function App() { return ( <View style={styles.box}></View> ) } const ...

What is the best way to integrate PHP scripts into jQuery?

I need help integrating PHP into my jQuery sample. Specifically, I would like to insert a PHP variable ($sample) into the "var para1" in the code below. var storyIndictor = jQuery(_storyIndictors[position]); var _content = jQ ...

The jQuery namespace does not function as intended

Whenever I attempt to execute the code below, I consistently encounter an error message indicating that .call is not a function. I am puzzled by this issue as the code appears to be quite simple. It seems like I am overlooking something obvious here. Your ...

Creating a Functional Right Arrow on a Pure CSS Select Menu/Dropdown

I have implemented a custom select/dropdown menu by following the solution provided here: The functionality works well, but I am facing an issue where the dropdown options only appear when clicking on the box. Clicking on the 'arrow' located on ...

Guide on transferring information from an HTML div to a MySQL database using JavaScript and PHP

function calculateNetTotal() { var net_total = 0; $('.qty').each(function() { var row = $(this).parent().parent(); var price = row.find('.price').val(); var total = price * $(this).val() - 0; row.find('.to ...

What is the best way to manage the maximum number of concurrent AJAX requests?

I am currently working on an autocomplete search bar feature. <input type="text" class="form-control" id="text" > <script> $("input").keyup(function(){ let key = $("input").val(); ...

React Card with Overflowing TableCell Texts

I am facing an issue with a table inside a table card where the TableCell is overflowing horizontally when the word is too long. How can I break it to the next line? Please refer to the "code" section for details. For more information, please visit my cod ...

Stop vertical scrolling in a designated div container

I am dealing with a div that is overflowing, but the horizontal scroll bar is not visible. How can I prevent actual scrolling on the div when the user attempts to scroll using the mouse or arrow keys? Below is the code for this div and a snapshot <!- ...

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: https://i.sstatic.net/1wtit.jpg Here is the HTML code that I have implemented so far: < ...

The hover effect is not functioning properly after loading jQuery with load();

When loading elements into a div using the load() function, I noticed that the :hover effect in CSS stops working for those elements. It's a dynamic menu setup, as shown below: <div id='main-menu'> <ul> <li class='click ...

Passing parameters through the URL with Angular's ui-router

Instead of passing parameters when changing pages like this: $state.go('index.my_route', {my_param : value}); Is it possible to pass the parameter in the URL string while still using $state.go? For example: $state.go('index.my_route?my_pa ...

Having difficulty utilizing Objects.key.map() for mapping purposes

I'm struggling to display my cart status in a JSX table and facing challenges. The state Chrome Console shows this Object output: { "cartItems": { "5": { "id": 5, "name": "Aut assumenda.", "price": 526, "quantity": 1, ...

"When a Vuex mutation modifies the state, the computed property fails to accurately represent the changes in the markup

I've encountered a perplexing issue with using a computed property for a textarea value that hasn't been addressed in a while. My setup involves a textarea where user input is updated in Vuex: <textarea ref="inputText" :value="getInputText" ...