When I attempt to edit a specific element by clicking on the edit button, all the other elements also respond to the click event instead of just the one I intended to

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="UTF-8">
<title>todo</title>
</head>
<body>
<div class="container"&pgt;
<h1 class="text">To Do App</h1>
<hr>
<div class="input">
<input id="input-text" type="text" name="" value="">
<button id="btn">Add</button>
</div>
<div class="to-do">
<h3 class="text color1">TO-do-list</h3>
<hr>

<ul id="toDoList">


</ul>
</div>
</div>

<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src= "js/todo.js"></script>
</body>
</html>

$('#btn').on('click', function() {
  let newTask = $('#input-text');
  if (newTask.val() === '') {
    alert('You need to write something');
  } else {
    let editButton = ('<button class = edit > Edit' + '</button>');
    let finishedButton = ('<button class = finished > Finished' + '</button>');
    let deleteButton = ('<button class = delete > Delete' + '</button>');

    let input = `<input disabled  value="${newTask.val()}" >`;

   
    $('#toDoList').append('<li>' +input+ editButton + finishedButton + deleteButton + '</li>');
 
    newTask.val('');
  }
  
  $('.edit').on('click', function() {
    $('input').prop('disabled',false);
  });
  
  $('.finished').on('click', function() {
    $(this).parent();
    $('#completed').append($(this).parent());
  });

  $('.delete').on('click', function() {
    $(this).parent().fadeOut(500, function() {
      $(this).remove();
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

There is an issue when I click on the edit button as all other elements also respond to the click event. It's my first experience with coding, so I'm unsure if there are any other issues in my code. Thank you in advance for your help.

Answer №1

The issue lies within this block of code:

  $('.edit').on('click', function() {
    $('input').prop('disabled',false);
  });

This code essentially states that all elements with the class 'edit' will enable all 'input' elements by removing the disabled attribute.

To address this, you must ensure that the functionality only applies to the specific element you intend to modify.

I have made a minor adjustment here

as a demonstration. I introduced a counter named 'count'. Each time an item is added, the count is incremented by 1 (count++) and stored in a data- attribute on the button.

Additionally, I assigned a unique ID to the textfield as 'field'+count so it aligns with the edit button link.

By observing the onclick event now utilizes the data attribute from each edit button to modify the respective field.

There are various methods to achieve this goal, but this example illustrates the problem-solving approach.

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 are some ways to customize the player for Youtube videos?

I'm looking to recreate the design of Youtube videos on my website when I embed them. The image below is just an example, but it reflects the simplicity I am aiming for. Any guidance or examples would be greatly appreciated, as I am unsure where to be ...

Alert: The specified task "taskname" could not be located. To proceed with running grunt, consider using the --force option

My current task involves converting .css files to .sass files using the 'grunt-sass-convert' npm module. Here is the configuration in my 'Gruntfile.js': 'use strict'; module.exports = function(grunt){ grunt.loadNpmTasks( ...

Is jquery.validate showing errors more than once?

For my testing program, I utilize the jquery.validate plugin to validate user input fields. Here is how it's set up: <script src="js/jquery-1.12.4.min.js"></script> <script src="js/jquery-form-3.51.min.js"></script> <script ...

`Trouble with CSS Measurement Properties in Internet Explorer 10`

(In the past, I relied on conditional IE statements to exclude a portion of my website from IE Browsers. Unfortunately, this method is no longer supported in IE10.) Currently, I have three images displayed on the header of my site, stacked one on top of t ...

Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the ...

List without order - item position in the list

I currently have a website featuring 5 pages, with the main navigation displayed using an unordered list. My goal is to have the "active" page displayed first in the list. For example, if my pages are "Home | About | Contact | Blog" and the user is on the ...

Having trouble with Typeahead Bootstrap not displaying dropdowns for ajax calls?

Utilizing Bootstrap 3 with the compatible Typeahead extension (https://github.com/bassjobsen/Bootstrap-3-Typeahead). The website operates on Django, and the query fetches information from a local Postgres server. Experiencing issues with displaying dropd ...

It is not possible to use Date.now within passport.js

When creating a user via Facebook on my Node.js website using passport, I want to assign the register date. In my Mongoose Schema, I can use the following for the local provider: regisDate: { type: Date, default: Date.now }, However, when it co ...

get value from json with specified key

Here is a function that handles the success of my AJAX call: success: function(responseJson) { var receivedData = []; $.each(responseJson.jsonArray, function(index) { $.each(responseJson.jsonArray[index], function(key, value) ...

"Incorporate React Redux to dynamically load an endless stream of items in batches of x at a time

In order to efficiently display search results using React - Redux, I want to limit the number of displayed results while maintaining optimal performance. Here is my current approach for getting and displaying the results: handleSubmit(event) { event ...

A URL that quickly updates live content from a backend script

As a beginner, I am seeking guidance as to where to start on my journey of learning. I need assistance in creating a script that can efficiently fit within a small URI space and constantly updates itself with information from a server script. My target bro ...

Steps for creating an HTML report using Intern JS

Our team relies on intern JS for automating functional tests, however we are facing difficulty in generating an html report. I attempted to use locvhtml as suggested by the Intern documentation (https://theintern.github.io/intern/#reporter-lcov), but unfo ...

What is the best way to add content to fill the empty space left after a column has been hidden in a column

Is there a way to automatically adjust the space when a column is hidden by clicking on the legend item? <div id="container" style="height: 300px"></div> <script src="http://code.highcharts.com/highcharts.src.js"></script> var ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

Can Vue recognize array changes using the Spread syntax?

According to Vue documentation: Vue is unable to detect certain changes made to an array, such as: Directly setting an item using the index, for example vm.items[indexOfItem] = newValue Modifying the length of the array, like vm.items.length = newLength ...

Script to Trigger Download Button

I'm having trouble with a rar file download on my website (ravens-hangar.tk). A bunch of lines of script keep popping up. Can anyone help me out? Thanks in advance! .download { width: 120px; height: 30px; font-size: 20px; text-align: center ...

What is the best way to refresh flexslider after it has been updated via AJAX?

At first, my slider is functional upon loading the page. However, after making an ajax call and receiving new slides to populate the slider, it becomes deactivated (as expected) https://i.sstatic.net/LC0yG.png Is there a method to reinitialize the flexsl ...

The jQuery function is running double even after I cleared the DOM with the empty() method

Twice, or multiple times if going back and forth, the Jquery function is triggered. Upon loading LoginMenu.jsp, WorkOrder.jsp is loaded within a specified ID. Once WorkOrder.jsp loads, it then loads schedule.jsp in the schedule tab defined in WorkOrders.j ...

What is the best way to make my navbar adjust seamlessly to accommodate the largest element?

Currently, I'm facing an issue where my logo is not fitting properly inside my navbar and it's "falling out." You can see the problem here: https://i.sstatic.net/l4T1B.png Here is the relevant code: HTML: <nav class="container-fluid navbar ...

The success handler is not being triggered by the Ajax call

Here is a situation I am struggling with: My Current Scenario I have a MVC ActionResult that is returning a Json: public ActionResult GetUpdates(string productId) { var updatesForProduct = _repository.GetUpdates(productId); if (updatesForProduc ...