Editing text using jquery

I'm currently working on creating a basic product list with the ability to edit each product. My challenge right now is figuring out how to enable editing by double-clicking on a product. Since English isn't my first language, I hope you can understand me clearly. Below is the code snippet:

<div class="container">
    <h1>Product List</h1>
    <input type="text" name="newProduct" id="newProduct" placeholder="Enter your product here"/>
    <ul id="productList"></ul>
    <input type="checkbox" id="selectAll"/><label for="Select all">Select all</label>
    <button id="deleteDoneProducts">Delete Selected</button>
</div> 

CSS

* {
    box-sizing:border-box;
}
body {
    font-family: Tahoma, sans-serif;
}
.container {
    margin:0 auto;
    width:600px;
}
h1, #newProduct {
    text-align: center;
    width:598px;
}
    #newProduct {
    border:1px solid #999;
    padding: 20px;
    font-size: 28px;
    box-shadow: 0px 0px 3px #888;
}
#productList {
    list-style: none;
    padding-left:0;
    background-color: #F2F2F2;
}
.product {
    padding: 15px 0px 15px 40px;
    margin: 10px;
    position: relative; 
    font-size: 24px;
    box-shadow: 2px 2px 3px #848484;
    background-color: #fff;
    cursor: pointer;
    text-transform: capitalize;
    color:#000;
    overflow: hidden;
}
.product:hover {
    background-color: #F2F2F2;
}
.doneProduct {
    margin-right: 40px;
}
.remove {
    background-image: url(ico/delete_ico.png);
    background-position: 0 0;
    width:30px;
    height: 30px;
    position: absolute;
    right: 20px;
    top:13px;   
    display: none;
}
.remove:hover {
    background-position: -34px 0px;
}
.product:hover .remove {
    display: block;
}
#deleteDoneProducts {
    float: right;
    background-color: #a3d5df; 
    color: #fff;
    padding: 10px;
    border: none;
    text-transform: uppercase;
    font-weight: 900;
}
#deleteDoneProducts:hover {
    background-color: #5fb5c7;
    cursor: pointer;
}

jquery

function addNewProduct(e) {
    if(e.keyCode == 13) {
        var toAdd = $('input[name=newProduct]').val();
             $('#productList').append('<li class="product"> <input     type="checkbox" class="doneProduct"/>'+toAdd+'<div class="remove"></div><li/>');
             $('#newProduct').val('');
             e.preventDefault();
    }
};

function deleteProduct() {
    $(this).parent().remove();
};


function productDone() {
    if (!$(this).is(":checked")){
        $(this).parent().css({'textDecoration': 'none', 'color': '#000'})
    } else  {
        $(this).parent().css({'textDecoration': 'line-through', 'color':     '#999'});
    };
};

function deleteAllSelected() {
    $(".doneProduct:checked").parent().remove();
    $('input[type="checkbox"]').removeAttr("checked");
};

function selectAllProducts() {    
    if (!$(".doneProduct").is(":checked")) {
        $(".doneProduct").prop('checked', this.checked);
        $(".doneProduct").parent().css({'textDecoration': 'line-through',     'color': '#999'});

    } else {
        $(".doneProduct").parent().css({'textDecoration': 'none', 'color': '#000'});
        $(".doneProduct").prop('checked', this.checked);
    }

};                

$(function() {
     $("#newProduct").on('keypress', addNewProduct);
     $(document).on('click', ".remove", deleteProduct);
     $(document).on('change', ".doneProduct", productDone);
     $("#deleteDoneProducts").on('click', deleteAllSelected);
     $("#selectAll").on('click', selectAllProducts);
     $(".product").on('dbclick', editProductName);

}) 

https://jsfiddle.net/qp3nnfc5/5/ - this is fiddle)

Answer №1

Check out this interactive example:

Modify your addNewProduct function like this:

function addNewProduct(event) {
    if(event.keyCode === 13) {
        var newItem = $('input[name=newProduct]').val();
        $('#productList').append('<li class="product"> <input type="checkbox" class="doneProduct"/><span>'+newItem+'</span><div class="remove"></div><li/>');
        $('#newProduct').val('');
        event.preventDefault();
    }
}; 

Also, include this in your JavaScript code:

$("#productList").on("dblclick","li",function(){
    $(this).find('span').attr("contentEditable",true)
})

Update :

For the latest version of the example, make sure to apply these changes:

Add this snippet to your JS file as well:

$("#productList").on("keypress","li",function(e){
    if(e.which == 13){
         e.preventDefault()
        $(this).find('span').attr("contenteditable",false)
        return;
    }
})

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

CSS - I add space between the components of the layout, but the color of the space does not match the body color

I am aiming for my website layout to have distinct margins between the left and right side of the content, as well as between the header and navbar. However, I do not want these spaces' colors to change to match the body's background color. http ...

I'm curious about this specific expression in express.js - can you explain its significance?

Could you please provide a thorough explanation of the following line of code in NodeJS: var app = module.exports = express.createServer(); ...

Trouble with getting a reply while using AJAX, jQuery, and PHP

I'm currently exploring how to transmit values and receive the appropriate response, but the only response I'm receiving is 0. Below is the AJAX code and form I've been utilizing: <script type="text/javascript"> $(document).ready(fun ...

Decode a URL that has been encrypted using JavaScript Base64 in Objective-C

I am attempting to decrypt a URL that was generated in JavaScript. This is the code snippet I found in the HTML page: Base64.encrypt(Base64.decode('Zk05NUQ6YUZVcERKd3pCdlkucUIrbnFtdldTdW5mbkZnZFk5TVFpV3N0NHRaTF9FV1RWSHhjX1pFMDNacmxwUy5JalF3Yw==' ...

Is it possible to resize a Div using pure CSS?

Here is the HTML structure I am working with: <div class="outer"> <div class="inner"> <a href="#"/> <a href="#"/> <a href="#"/> </div> </div> This is the corresponding CSS: div.outer{ position:relative; ...

Utilizing Gulp locally without the need for global installation or referencing the bin js file

I have a gulpfile.js that runs perfectly when I type 'gulp' into the command line. Essentially, the 'gulp' bash command just calls the specific js file outlined in 'package.json >> bin >> gulp' of the globally ins ...

Guide on incorporating a CARTO map into your react.js code

I'm currently facing a challenge as I attempt to connect a CARTO map (created using the CARTO builder) with react.js. My roadblock is with employing carto.js via cartoclient: this.cartoClient = new carto.Client({ apiKey: 'key', username: & ...

Changing Value in jQuery Dropdown Menu

I currently have two JQuery UI dropdowns. When I select an option in the first dropdown and set a checkbox to true, I want to copy that selected value to the second dropdown using the .change() event of the checkbox. To retrieve the selected value, I use ...

Having trouble removing lines from Router Link? Unfortunately, using style={{'textDecoration': 'none'}} doesn't seem to be doing the trick

Does anyone know why the text decoration is not working on my link when I use text-decoration none? Any solutions or suggestions would be greatly appreciated. Thank you in advance! Navbar.js file import React,{useState} from "react"; import { mak ...

The HiddenField is returning empty when accessed in the code behind section

In my gridview, the information is entered through textboxes and saved to the grid upon clicking a save button. One of these textboxes triggers a menu, from which the user selects a creditor whose ID is then saved in a HiddenField. <td class="tblAddDet ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

Incorporate an Angular app into an existing application and seamlessly transfer the data

I am currently in the process of integrating an Angular app into an existing jQuery application. Let's say I have a basic button in my HTML code. My goal is to load the Angular app and execute controller code when the button is clicked. To achieve t ...

Arrangement of Digits within a String

I need a regex that can capture strings in groups of three, but if the remaining characters are not divisible by three, I want them grouped in twos. For example: 123456 should be 123 456 1234567891011 should be 123 456 789 10 11 Could someone please ass ...

Can .NET MVC be used to host vue.js static files?

I recently received a sample Vue app created using vue-cli, which generates static files when the npm run build command is executed. Normally, these files are served by a server from node.js. However, I am curious to know if it's possible to serve th ...

Updating a jQuery variable through an AJAX request

Is there a way to update a variable that is located outside of an AJAX call from an event that is inside this AJAX call? This snippet of code shows that the var units is initially set to metric, but when a selectbox changes (inside the AJAX call), I want t ...

Determine the vertical dimension of the containing element

<div class='contain'> <a href="#"> <div id="s1" class="sub" onclick="hello('1')">dasdad</div> </a> </div> <div class='contain'> <a href="#"> < ...

Error encountered in loop for concatenating html elements: identifier unexpectedly found (jquery + html + php)

I am attempting to concatenate HTML inside a variable within a loop and then return it populated. However, I am encountering an error: Uncaught SyntaxError: Unexpected token += in my code. <a style="cursor: pointer" id="addmore">More Entree ?</ ...

The entirety of the text has been mirrored to the right in React Native code

Is there a way to align this text on both the left and right sides, along with styling the button and text input elements to be more colorful and have bigger fonts? Below is an example of the desired outcome: This is what I have attempted so far: <Vie ...

User interface design for node.js and jquery web applications

When using node.js for web applications, is there a preferred UI framework to pair with it? Or is this an independent consideration? While jQuery is popular, is jQuery UI the most commonly used UI framework with the jQuery engine? Ar ...

At what point should you invoke db.close() while utilizing cursor.forEach()?

When working with .toArray(), it is common practice to include db.close() within the callback function. For example: db.collection('grades').find(query).toArray(function(err, docs) { if (err) throw err; console.dir(docs); db.close(); }); ...