Effortless Editing and Saving with JQuery

Looking for help with jQuery Inline Edit operations. I currently have a setup where:

Label Name   ------>  Edit button

and when the edit button is clicked, the label name is replaced with an input text box and edit button is replaced with save and cancel buttons.

 Input text   ------>  save and cancel button

My goal is to enhance this functionality by allowing the same class names for all label/edit/save/cancel buttons within multiple divs. Each div will have a unique Id for the input_text field. When clicking on Div1, it should update values for Div1, and so on for other divs.

If you want to see the code in action, check out this link.

html

<!-- Label one -->
<div>
    <label class="name">
        <span>Label 1</span>
    </label>

    <input id='text_1' class='com_text' type='text' />  
</div>

<div>       
    <a href='#' class='edit'>
        <span>Edit</span>
    </a>

    <button class='save' type='submit'>Save</button>

    <button class='cancel' type='reset'>Cancel</button> 
</div>
<!-- Label one --> 
<br/>
<!-- Label two -->
<div>
    <label class="name">
        <span>Label 2</span>
    </label>

    <input id='text_2' class='com_text' type='text' />  
</div>

<div>       
    <a href='#' class='edit'>
        <span>Edit</span>
    </a>

    <button class='save' type='submit'>Save</button>

    <button class='cancel' type='reset'>Cancel</button> 
</div>
<!-- Label two -->
<br>
<!-- Label three -->
<div>
    <label class="name">
        <span>Label 3</span>
    </label>

    <input id='text_3' class='com_text' type='text' />  
</div>

<div>       
    <a href='#' class='edit'>
        <span>Edit</span>
    </a>

    <button class='save' type='submit'>Save</button>

    <button class='cancel' type='reset'>Cancel</button> 
</div>
<!-- Label three -->

JQuery

$(document).ready(function()
{
    $('.com_text').click(function()
    {
        var com_text = $(this).attr('id');
    });

    //Edit
    $('.edit').click(function()
    { 
        $(this).hide();
        $('.name').hide();
        $('.save,.cancel').show();
        $(com_text).val($('.name').text().trim()); 

    });

    //Cancel
    $('.cancel').click(function()
    { 
        $(this).hide();
        $('.name,.edit').show();
        $('.save').hide();
        $(com_text).hide();
        $(com_text).val('');

    });

    //Save
    $('.save').click(function()
    { 
        var sname = $(com_text).val().trim();

        var dataobj = {};
        dataobj.sid = $(this).attr('data-id');
        dataobj.sname = sname.trim();

        $.ajax(
        {
            type:"POST",
            dataType:"json",
            url:"pages/demo.php",
            cache: false,
            data: dataobj,
            success:function(response)
            {   
                $('.name').html(sname.trim());
                $('.name,.edit').show();
                $('.save,.cancel').hide();
                $(com_text).hide();
                $(com_text).val('');                                                            
            }
        });
    });
});

Answer №1

Hey there, take a look at this JavaScript code that I've made some modifications to:

 $(document).ready(function()
{
    $('.com_text').click(function()
    {
        var com_text = $(this).attr('id');
    });

    //Edit
    $('.edit').click(function()
    { 
        $(this).hide();

        $(this).parent().prev().find('.name').hide();
       $(this).parent().prev().find('input').show();
        $(this).next('.save').show();
        $(this).next().next('.cancel').show();

        $(com_text).val($('.name').text().trim()); 

    });

    //Cancel
    $('.cancel').click(function()
    { 
        $(this).hide();
        $(this).parent().prev().find('.name').show();
        $(this).parent().prev().find('input').hide();
        $(this).prev().hide();
        $(this).prev().prev().show();
        $(com_text).hide();
        $(com_text).val('');

    });

    //Save
    $('.save').click(function()
    { 

        var sname = $(this).parent().prev().find('input').val().trim();
   alert(sname);

 $(this).parent().prev().find('.name > span').text(sname);
        $(this).parent().prev().find('.name').show();
        $(this).parent().prev().find('input').hide();
        $(this).prev().show();
        $(this).next().hide();
        $(this).hide();


    //  var dataobj = {};
    //  dataobj.sid = $(this).attr('data-id');
    //  dataobj.sname = sname.trim();

    /*  $.ajax(
        {
            type:"POST",
            dataType:"json",
            url:"pages/demo.php",
            cache: false,
            data: dataobj,
            success:function(response)
            {   
                $('.name').html(sname.trim());
                $('.name,.edit').show();
                $('.save,.cancel').hide();
                $(com_text).hide();
                $(com_text).val('');                                                            
            }
        });*/
    });
});

Check out the Jsfiddle demo here

Second demo link

Answer №2

This useful tool can be implemented with the help of a specific plugin.

Check out the plugin here

Answer №3

After reviewing your code, I have successfully resolved errors and improved the display functionality. Additionally, here is a valuable tip to guide you towards achieving your desired outcome.

Tip: Incorporate wrappers into your code structure.

Instead of:

<!-- Label one -->
<div>
    <label class="name">
        <span>Label 1</span>
    </label>

    <input id='text_1' class='com_text' type='text' />  
</div>

<div>       
    <a href='#' class='edit'>
        <span>Edit</span>
    </a>

    <button class='save' type='submit'>Save</button>

    <button class='cancel' type='reset'>Cancel</button> 
</div>
<!-- Label one --> 

You can enhance the organization of your code by wrapping each label within a div element, creating a structured hierarchy and delineation between items as shown below:

<!-- Label one -->
<div class="label-1 item-container">
    <div>
        <label class="name">
            <span>Label 1</span>
        </label>

        <input id='text_1' class='com_text' type='text' />  
    </div>

    <div>       
        <a href='#' class='edit'>
            <span>Edit</span>
        </a>

        <button class='save' type='submit'>Save</button>

        <button class='cancel' type='reset'>Cancel</button> 
    </div>
</div>
<!-- Label one --> 

Some developers opt to use list items for this purpose, which can also be effective. While it may not significantly impact SEO, it contributes to a more coherent structure.

Incorporating wrappers and defining boundaries will prove beneficial in isolating specific elements from unwanted script interference.

To achieve your desired functionality, there are numerous approaches available, with jQuery being a common solution for such tasks.

Instead of employing a generic selector for every element, consider traversing the DOM relative to the context using jQuery's $.closest() and $.find() functions.

For example, refer to this jsFiddle demonstration.

In the provided example, I introduced wrappers around each element and utilized

$.closest() to navigate upwards in the DOM | View Closest Documentation

and

$.find() to search downwards in the DOM | View Find Documentation

I trust that this response proves enlightening and assists you in your coding endeavors!

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

What is the best way to enhance the appearance of the unordered list within the pagination design?

I'm struggling to apply styles to the ul within the Pagination, no matter what I try, it just doesn't seem to work! Here is an image for reference: https://i.sstatic.net/lQvPn.png I am trying to target the MuiPagination-ul class for styling ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

Unusual patterns appearing in HTML image files

As a beginner in html, please pardon my silly questions and mistakes. I have designed this webpage: <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <style type = text/css> #topbar { ...

Enhancing DataTable Performance with Django Filters

I have implemented a feature where users can apply filters to customize the data displayed in a Table. When a user interacts with these filters, an asynchronous Ajax call is triggered: $.ajax({ url: '/fund_monitor/fund_directory&a ...

Showing a hidden div after an unsuccessful AJAX call

Encountering an issue with displaying a div notification using the code snippet below: $.ajax({ url: url, cache: false, async: false, success: function (data) { response = jQuery.parseJSON(data); }, error: functi ...

Activate a Tab using JavaScript in Vue.js

Hello there, currently working with Vue and Bootstrap-Vue. The scenario is as follows: I have designed a registration page with 2 tabs. The user needs to complete the first tab before moving on to the second one by clicking a button. The second tab initia ...

The primary container is brimming with an abundance of content

Can anyone help me with a CSS issue I'm experiencing in the latest versions of Chrome and Firefox? I can't seem to figure it out on my own. The problem arises with a container div that has a 50px top margin. Inside this container, there's a ...

I am looking to include both the type and maxLength attributes in a MUI TextField

<TextField value={ele.mobile} helperText={ferrors[id]?.mobile} name="mobile" classes={{ root: classes.textField }} InputProps={{ clas ...

The height of the second jQuery dialog is being influenced by the height of the previous

Having an issue with the height of my jQuery dialog box when opening a second dialog from a previous one. The first dialog is displaying correctly at 200 x 200 dimensions, but when clicking the OK button to close it and open a new dialog at 400 x 400 dimen ...

Unable to confirm authenticity of dynamic form using PHP

I seem to be encountering an issue while attempting to validate my dynamic HTML form using a PHP script. Upon clicking submit, I receive an error stating that there is an undefined index, even though the index is clearly defined. What sets my query apart f ...

Utilizing Jquery for draggable/droppable functionality in combination with custom overflow styles

Encountering a challenge with a drag and drop system that utilizes CSS overflow properties to enable vertical scrolling of a list of values. The issue arises when dragging an item between selected and unselected areas, causing the dragged item to disappear ...

Interacting with Local Databases Using HTML and JavaScript

I am looking to create a website that can be stored on a USB stick and opened in a browser. The HTML file should be able to access a database (sql) located in the same folder using JavaScript. This is a small project for me. The files I have are as follows ...

The loading GIF in jQuery is malfunctioning when displayed simultaneously on multiple div elements

I am currently working on my Laravel dashboard's blade to showcase various statistics. These stats will be updated whenever the date picker is changed. Below is the code for my date picker: <div class="row"> <div class=&qu ...

Reinitialize a dynamic array using jQuery

Whenever I click a button, a function adds a variable number of numbers to an array dynamically. Here is the code snippet: $('#calculate').click(function(e) { var foo = $(".foo"), A = [], B = []; //Push values foo.each(functi ...

Issue with Slick Grid not updating after Ajax request

I need to update the data on a slick grid when a checkbox is clicked, using an ajax call to retrieve new data. However, I am facing issues where the slick grid does not refresh and the checkbox loses its state upon page load. Jsp: <c:if test="${info ...

Hide the search bar's input field

I'm in the process of creating a responsive blog with a search input feature. However, I've encountered an issue where the search form input in my sidebar isn't collapsing properly and is overflowing outside of its designated container. Belo ...

Here's a guide on how to display texts underneath icons in Buttons using Material UI

Currently, this is the Button I have displayed https://i.sstatic.net/YkHp0.png I am trying to figure out how to position the Dummy Button text beneath the icon. Can someone assist me with this? Below is my code snippet: <Button className={classes.d ...

Sending information back to a jQuery/AJAX request from an Entity Framework object in an ASP.NET application

I'm attempting to retrieve a List<Product> from Entity Framework using a jquery/ajax call. Here is the ajax request I have written. $.ajax({ type: "POST", url: "searchService.asmx/search", data: "{'looku ...

Uncovering concealed data in job listings by utilizing BeautifulSoup

Hey there! Currently, I am enrolled in a python course and our assignment for today involves extracting job listings from this website: I have attached a screenshot of the HTML related to this task here: python jobs f12 This is what I have managed to com ...

Issue with fixed sidebar on brief content

It's interesting how the sticky widget performs differently on long articles compared to short ones on my website. Here is an example of a long article where the sticky widget works well without any lag: . Now, let's take a look at a shorter art ...