Tips for creating a jquery modal form that can be reused

I currently have the following files :

*vehicule_parc.php :*

<script language=javascript src="../js/vehicule_parc.js"></script>
<h3 class="headInfoBox" id="cch">Fuel Consumption >></h3>
<hr />
    <div id="cc">           
        <table cellpadding="0" cellspacing="0" border="0" class="display boxtable" id="consoTable">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Time</th>
                    <th>Quantity</th>
                    <th>Cost</th>
                    <th>Card</th>
                </tr>
            </thead>
            <tbody>
                <tr class="odd gradeA">
                    <td>21/03/2011</td>
                    <td>10:00</td>
                    <td>30</td>
                    <td>40</td>
                    <td>02248</td>
                    </tr>
            ...
    </div><!-- cc -->
<button id="addcc">Add</button>
<?php include 'form_conso_carb.html'; ?>

*form_conso_carb.html :*

<div id="form_conso_carb" title="New Consumption">
    <form>
        <label for="date">Date</label>          <input type="text" name="date"      value="" />
        <label for="time">Time</label>        <input type="text" name="time"     value="" />
        <label for="quantity">Quantity</label>     <input type="text" name="quantity"  value="" />
        <label for="cost">Cost</label>          <input type="text" name="cost"      value="" />
        <label for="card">Card</label>            <input type="text" name="card"     value="" /> 
    </form>
</div>

*vehicule_parc.js :*

   //some code before
    J( "#form_conso_carb" ).dialog({
            autoOpen    : false,
            height      : 'auto',
            width       : 300,
            modal       : true,
            position    : 'middle',
            Cancel  : function() {
                        J(this).dialog( "close" );
                    },
            buttons : {
                "Send"   : function() {

                            }
            }
        });

        J( "#addcc" )
        .button()
        .click(function() {
            J( "#form_conso_carb" ).dialog( "open" );
        });
        //some code after

My objective is to extract and reuse the code in vehicule_parc.js into a standalone file. However, the code must be aware of the table id - in this case id="consoTable" - in order to perform AJAX on the table. And ideally, I would like to include form_conso_carb.html in that same file as well.

The main goal here is to easily implement a modal form for CRUD operations on the consoTable.
I hope my explanation is clear.

Answer №1

Transform it into a function and utilize this within the click event to access the current object and pass it as an argument:


function openDialog(element) {
       $(element).dialog({
            autoOpen    : false,
            height      : 'auto',
            width       : 300,
            modal       : true,
            position    : 'middle',
            Cancel  : function() {
                        J(this).dialog( "close" );
                    },
            buttons : {
                "Send"   : function() {

                            }
            }
        });
}

J( "#addcc" )
.button()
.click(function() {
openDialog(this);
});
}

Answer №2

I found the solution on a French website called alsacreations. The recommendation is to encapsulate the code, similar to this example, and save it in a separate file:

var activeJsLib = (function() { 
  // Private members 
  function init() { 
    activeJsLib.addClass(document.body, activeJsLib.newClass); 
  } 

  if (document.getElementById && document.createTextNode) { 
    window.onload = init; 
  } 

  // Public members 
  return { 
    "addClass": function(element, className) { 
      if (element.className) { 
        element.className += " "; 
      } 

      element.className += className; 
    }, 

    "newClass": "jsActive" 
  }; 
})();

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

Using three.js to showcase a sequence of various objects consecutively

I am currently working with three.js to create mesh and textures for 20 different objects. Below, you will find an example object. My goal is to display each of these 20 objects sequentially on the screen. I want to show the first object, have it stay on ...

Is there a way to connect two circles with identical numbers using Javascript and HTML?

My latest project involves creating a fun program that generates 4 balls on the screen, each with a unique number displayed inside. Users can input their desired values for new circles to be generated and then click a button to see four more balls appear ...

Saving a CSS-styled image to a database: A step-by-step guide

I have an image and I want to apply CSS effects such as blur to it. After applying the effect, I need to save the modified version of the image in the database. How can I achieve this? Here's my code: Html: <img src="avatar.jpg" class="blur">&l ...

Manipulating child elements in XML, JavaScript, and jQuery – the possibilities are endless!

I have a good grasp on how to extract elements and write them to a document in JavaScript using the HttpXMLRequest object. However, I am struggling to find resources that explain how to modify it further. I believe part of the issue is that I am unsure of ...

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...

Finding the substring enclosed by two symbols using Javascript

I'm working with a string that contains specific symbols and I need to extract the text between them. Here is an example: http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_se ...

Search for Azure Time Series Insights (TSI) data insights

Is there a way to access real-time data from Azure TSI using the TSI query API? I am currently utilizing the TSI JavaScript Client library, which provides two wrappers for the Query API. However, these wrappers only allow me to retrieve aggregate data li ...

Issue with running "ng serve" command on command prompt

Upon running the command "ng serve" in cmd for Angular2, I encountered the following errors: "unknown browser query basedir=$(dirname $(echo $0 | sed -e s,\,/,g))" After multiple attempts to resolve the issue, I found the error message: Browsersl ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

Utilize the automatically generated objectId or generate a custom Unique ID to map classes within Parse

We are looking to upload a large amount of data to our mobile backend on Parse. Our data consists of two classes - Store and Product. A store can have multiple products, while each product belongs to only one store. We want to streamline this process by bu ...

JavaScript: Receiving Varied Outputs from Comparable Functions

Here are two code snippets that contain an object and a function, both with identical content. They should theoretically return the same value. The only difference between the two is the presence of brackets and an 'else' statement in the 'f ...

jquery autocomplete utilizing an external json data feed

I am facing an issue with my autocomplete function that was initially working with a local json source. I have decided to move it to an external json file, as my current code is lengthy (16k lines). However, I am struggling to make it work with the externa ...

How can I incorporate an input text field in a specific row of an ng-repeat table similar to the image provided?

I have a table created using ng-repeat and I am looking to add an input row for only one specific row, not all rows. How can this be done? This is my current HTML code, any suggestions on how I can achieve this? Thank you! ...

Using AngularJS to show/hide elements within a colgroup tag

Looking to create a dynamic table allowing users to hide certain columns. Wondering if it's possible to use ng-show with colgroup or col tags instead of adding ngshow to each cell individually. Struggling to make it work... <colgroup ng-repeat="mt ...

Searching for li elements that contain text values - a guide

I have a list of letters and I want to filter out any values that contain the text entered by the user in a textbox. Here is the design: Search List: <input type="text" id="txtSearch" /> <ul> <li>Coffee1</li> <li>Coffe ...

Exclude the CSS file from all elements except for the ones that are being appended to a specific div

Imagine you have a document with a CSS file that applies to all elements on the page. Is there a way to selectively remove or add styles from this file so they only affect a specific div and not the entire document? ...

Is it possible to simultaneously press two keys in WebdriverIO?

Currently, I'm working on writing code with WebdriverIO that involves pressing the shift and tab keys simultaneously. So far, I've successfully managed to press each key individually using browser.keys("\uE004"); and browser.keys("\uE0 ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Customize your DataGrid filtering with Material UI custom list filter feature

Exploring custom filters in the Material UI DataGrid has been an interesting experience for me. I found some useful information on https://material-ui.com/components/data-grid/filtering/ However, I encountered a challenge when trying to create a list with ...

Discovering if an element is present with Cypress.io

Is there a straightforward way to determine if an element is present, and then proceed with specific steps based on its presence or absence? I attempted the following approach, but it did not yield the desired results: Cypress.Commands.add('deleteSo ...