Tips for removing two specific "th" elements from a table that is generated dynamically

I have a challenge where I need to remove 2 specific elements from a table depending on which delete button is clicked

Check out the code snippet below :

<!--HTML-->
<button type="button" class="collapsible">Manage Formulas</button>
<div class="form-group content">
<br />
    <button type="button" class="add-formula"><i class="fas fa-plus-circle"> Add Formula</i></button>
    <div class="panel-body add-formula">
    </div>
</div>
// JavaScript
// adding formula
$('body').on('click', '.add-formula', function() {

    const $formula = $('<div>').addClass('formula-div');

    const $line_formula = $('<div>').addClass('line-formula');
    const $btn_formula = $('<th>');
    const $table_formula = $('<table class="table" id="formula">');
    const $head_formula = $('<thead>');
    const $tr_formula = $('<tr>');

    // code continues...

});

// adding field
$('body').on('click', '.add-field', function(event) {
    // function implementation here...
});

// deleting field
$('body').on('click', '.delete-field', function(event) {
    // function implementation here...
});

This does not behave as expected and I need it to work differently.

The current behavior is that clicking the "Delete" button removes an entire column.

What I expect is that when I click a delete button, the specific element related to that button should be removed along with the adjacent "Operator" element.

Please see the desired outcome in the provided screenshot :

Lastly, here's how you can interact with this code snippet :

Answer №1

If you want to target the button that was clicked using the jQuery variable $(this), you can use parent() to move up the DOM hierarchy. To access the next element, you can utilize next(), and for the previous element starting from that point in the DOM, you can employ prev().

To better illustrate this concept, here is a straightforward example:

$('button').on('click', function(){
  // Shows the button that was clicked on
  // console.log($(this));
  
  // Use parent to capture whole div
  var wrapper = $(this).parent();

  // Delete the previous 'deleteme', if no element is found, it does nothing
  wrapper.prev('.deleteMe').remove();

  // Delete first span after wrapper
  wrapper.next('span').remove()
  
  // Delete wrapper
  wrapper.remove();
        
});
.wrapper {
  border: 1px solid red;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <button id="1">Button 1</button>
  <p>Things that get deleted on button 1</p>
</div>
<span>Item that also will be deleted on button 1</span>
<p class="deleteMe">Item before that button 1 doesn't have</p>
<div class="wrapper">
  <button id="2">Button 2</button>
  <p>Things that get deleted on button 2</p>
</div>
<span>Item that also will be deleted on button 2</span>

Answer №2

Successful Solution :

// Remove field
$('body').on('click', '.spr-champs', function(event) {
    var th_spr = $(this).parent();
    var num_th = th_spr.parent().children(1).index($(this).parent());

    if (num_th == 2)
    {
        if (th_spr.next('th'))
        {
            th_spr.next('th').remove();
        }
        th_spr.remove();
    }
    else
    {
        th_spr.prev('th').remove();
        th_spr.remove();
    }
});

1) Identified the specific th using

var num_th = th_spr.parent().children(1).index($(this).parent());

2) Implemented a condition - if it's the first button: delete the field and the operator following it, else: delete the field and the operator before it.

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

Organize the structure of a JSON object in AngularJS to generate a hierarchical unordered list

Greetings! I am working with a RESTful API that returns a JSON object structured like this: { data: [ { id: 4, name: "Naranja", cant_portion: 2, portion_name: "Piezas", foodgroup_name: "Frutas" } ...

Validating Laravel emails with JavaScript blur and utilizing AJAX and jQuery

Looking for a way to validate a form in Laravel without hitting the submit button? I've tried some code, but only the email format validation seems to be working. Any tips on what I should do next? I'm new to Ajax. PS: When I enter a valid email ...

Track changes and save only the updated elements in an array

Currently, I am utilizing Angular for the front end, C# for the backend, and an Oracle database for a project with a company. Within the grids provided to me, there are more than 120 records that users can edit individually. My dilemma lies in identifyin ...

Achieve a disabled scroll bar feature on Firefox

I am experiencing an issue with a Javascript tabbed dialog where the pages have varying heights. Some of them are larger than the browser window. In Internet Explorer, there is always a scrollbar present on the right side. When it is not needed, it appear ...

How can I establish a connection with a MS SQL 2012 database using jquery?

I recently developed a web application using Sharepoint 2010 and successfully connected to a Sharepoint list through the REST API (ajax). This method enabled me to utilize a Sharepoint list as a database. Currently, I am in the process of setting up a web ...

Ensure that the textbox remains valid when the reset button is clicked in Bootstrap

After implementing the code for bootstrap textbox and textarea, I encountered an issue when using the reset button. When entering an invalid shop name followed by a valid address and clicking on the Reset button, it resets the form. However, if I then only ...

Can you reference document.styleSheets[].cssRules[] by specifying a rule name?

I am trying to modify a specific class property value in JavaScript without using an integer as a pointer or looping through all classes to find a matching selectorText value. This is specifically for changing the language displayed on the webpage. <s ...

Is it possible to make an HTML page permanent and uneditable?

Is it possible to secure my HTML file from being edited or modified, especially in a web browser? Discover innovative techniques and gain deeper insights into web development and website design. Interested in learning more about HTML, CSS, JavaScript, PH ...

Encountering an error in Selenium Python when using the second iteration of find_elements_by_xpath

I'm currently navigating through my college website dashboard to find all relevant subjects. I am utilizing selenium for this task. Due to the slowness of the site, I implement a waiting period. WebDriverWait(driver, 20).until(EC.element_to_be_clickab ...

Automatically create and display a jQuery popup and set it to disappear after a specified time

I am new to jquery and looking to create popups using data from a database. The popups should appear for a specific time duration also retrieved from the database. I have been working on this for the past 17 hours but haven't made any progress yet. ...

Determine the size of v-flex in Vue / Vuetify

Vuetify provides the v-resize directive, which is demonstrated in an example using window size. I am interested in utilizing this directive to monitor the size of a specific component (e.g. v-flex). In the provided codesandbox example, the objective is t ...

What is the significance of the expression $location.path() equal to '/a' in Angular?

I am currently delving into AngularJs for the first time and I have been studying the Angular documentation in order to grasp its concepts. While going through it, I came across this piece of code: $location.path() == '/a'. However, I am struggli ...

React Image Error Handling: How to deal with broken images in

I am currently working on a project where I need to retrieve the maxresdefault of various YouTube thumbnails. However, some YouTube videos do not have high-resolution thumbnail images available. To handle this scenario, I added an onError prop to the img ...

After Effects Script: Apply various character styles from main text to subtext

I'm currently working on an After Effects script that can transfer the style and text of a text layer to another text layer in a different comp. The script works perfectly if the parent text layer only has one style, but I need it to handle a situatio ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

"error: unable to retrieve message channel name, result is undefined

Hey there, I'm currently experiencing an issue while trying to retrieve the name of a channel that I created. Strangely enough, it's returning undefined, even though I am certain that the channel exists. Let me share with you the code snippet wh ...

When attempting to seed, the system could not locate any metadata for the specified "entity"

While working on a seeding system using Faker with TypeORM, I encountered an error during seeding: ...

Ways to stop the floating label from blending with the input field

Attempting to incorporate the Bootstrap Material design theme into my project, I have implemented a basic text input field using the code below: <div class="form-control-wrapper"> <input class="form-control empty" type="text"></input> ...

Cascading Style Sheets displaying inconsistently between local environment and server

Is it just me or does anyone else experience CSS behaving differently on a remote EC2 server compared to a local server? When I load the page and inspect it, I notice that different CSS rules are being applied. I've already executed collectstatic and ...

Splitting HTML content into pages according to the size of the content

I am currently working on a web application designed for editing documents. In this app, each document can consist of multiple pages, all following the standard paper size in Germany (DIN A4 with dimensions 210mm width x 297mm height). To ensure that the l ...