Searching for the row value of specific data within a table using Javascript

I have a PHP table populated with values, and I want to make two of the table data cells editable. The table headers include: Task, Due Date, Staff, and Department. The values in the table data are retrieved from a database using Laravel Eloquent.

<table class="table table-striped">
          <thead>
               <tr><th scope="col">Task</th><th scope="col">Due Date</th><th scope="col">Staff</th><th scope="col">Department</th></tr>
          </thead>
          @foreach($tasks as $task)

               <input type="text" id="taskid" name="taskid" value="{{$task->id}}" hidden>

               <tr class="tabletd"><td scope="col" >{{$task->task}}</td>
                    <td scope="col" contenteditable="true">
                         <input type="date" name="duedate" id="duedate" class='form-control form-control-sm' value="{{$task->duedate}}" style="width:135px;" >
                    </td>

                    <td scope="col">{{$task->user->name}}</td><td scope="col">{{$task->department->title}}</td>

               </tr></table>   @endforeach
     

I am utilizing AJAX to update these values on the server.

$(document).ready(function(){

          $(document).on('change','#duedate',function(){
               var duedate=$(this).val();
               var id = $('#taskid').val();
               $.ajax({
                    type:'get',
                    url:'{!!URL::to('duedateupdate')!!}',
                    data:{'id':id, 'duedate':duedate},
                    success:function(data){
                         document.getElementById("updatemsg").hidden = false; 
                         setTimeout( function (){
                              document.getElementById("updatemsg").hidden = true; 
                         }, 2000);
                    },
                    error:function(){

                    }
               });
          });
     

The code works fine, but it only updates the first row of the table. How can I extend this functionality to update values in the other rows as well?

Answer №1

The issue arises from using the input id "duedate"

Update the id to a class

<input type="date" name="duedate" class='form-control form-control-sm duedate' value="{{$task->duedate}}" style="width:135px;" >

In your event listener, utilize the class selector:

$(document).on('change','.duedate',function(){

This adjustment should yield the desired outcome

--- revision based on the following comment: -----

Take note of the selector here :
var id = $('#taskid').val();

Once again, refrain from using an id (which can only select one element), and opt for a data value in the input as shown below:

<input type="date" data-task-id="{{$task->id}}" class="duedate" class='form-control form-control-sm' value="{{$task->duedate}}" style="width:135px;" >

You can then reference this in your ajax code:

var id = $(this).data( 'task-id' );

If you encounter issues with data(), use the following approach:

var id = $(this).attr( 'data-task-id' );

Answer №2

After some code adjustments, I have successfully implemented the following updates:

<input type="date" name="duedate"  contenteditable="true" data-id="{{$task->id}}" data-column="duedate"  class="form-control form-control-sm duedate"  value="{{$task->duedate}}" style="width:135px;" >


$(document).on('change','.duedate',function(){
    var duedate = $(this).val();
    var id = $(this).data("id");
    $.ajax({
        type:'get',
        url:'{!!URL::to('duedateupdate')!!}',
        data:{'id':id,'duedate':duedate},
        success:function(data){

        },
        error:function(){

        }
    });
});

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

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Executing the command "node <app name>" does not result in any action

I am experiencing an issue with my bot app called "vgen.js". When I run the command "node vgen", the prompt/directory disappears and the cursor just blinks on the far left of the screen. I have been following instructions from a tutorial found here: https ...

Changing boolean values in Ruby on Rails articles

Within my 'comment' model, I have a boolean value that can be either true or false. The following excerpt is from my controller comments_controller.rb: class CommentsController < ApplicationController before_action :find_comment, only: ...

Guide to retrieving SQL data using Node.js with mysql2

I've decided to convert my code from Python to Node.js, and I'm encountering a problem when trying to retrieve data from SQL. In Python, it's simple to get the data, return it, and then use it in the code. Here is the Python code: def sql_g ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

Difficulty in displaying JavaScript function output as text

I'm currently developing a program that randomly selects and prints a function from an array list. I am facing difficulties in getting the result to print correctly. Below is the snippet of code: const hiddenElements = document.querySelectorAll( &qu ...

Using Jquery $.ajax may lead to temporary freezing of the Browser

I have a $ajax function that fetches multiple JSON objects from a URL and converts them into divs. There are around 50 objects, and I am using setInterval to call the $ajax function every 10 seconds for updates on each of the created divs. However, I' ...

Utilize VueJS to bind a flat array to a v-model through the selection of multiple checkboxes

My Vue component includes checkboxes that have an array of items as their value: <div v-for="group in groups"> <input type="checkbox" v-model="selected" :value="group"> <template v-for="item in group"> <input type ...

Discover the world of Google Chrome Apps with the power of chrome.storage.local

While building an application, I encountered a perplexing issue that I need help with: The task involves reading a JSON file and storing its content in localStorage using chrome.storage.local in a Chrome app. Here is a snippet from the JSON file: { "s ...

Guide to implementing input fields in a form in React.js when the user chooses the "Other" option from a dropdown menu

For my project, I have implemented a multi-select dropdown input feature that saves all selected items in a useState array when the user clicks on the add icon. However, I am facing an issue where I need to render an input field only when the "Other" optio ...

Activate an event on a shadow DOM element that is covered by an element in the light DOM (not directly related)

I am currently facing a challenge in retrieving the coordinates of a table cell within a shadow DOM. This table cell may have overlay elements displayed above it, which could span over multiple cells and may not necessarily be direct children of the cell I ...

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

Provide a response containing JSON data extracted from an HTML file

I am looking for a way to create a simple REST API using a hosting site that only allows hosting of HTML files along with JavaScript files. I want to be able to send POST/GET requests and receive JSON data in response. For instance, when making a GET requ ...

Can I simultaneously utilize submit and ajax functions?

As I work on CRUD for our website, the approach we are taking involves using submit. However, there are occasions where I need to pass data from a JS file to my controller (I am using Codeigniter). I am now considering whether it is common practice to do ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

How can we implement intricate looping mechanisms in hogan js?

Currently, I am in the process of familiarizing myself with expressjs. In my journey to learn this technology, I have encountered a controller that performs queries on a database and returns a JSON object with certain key-value pairs. An example of such an ...

jQuery disregards the else-if statement

Currently, I am developing a web application that prompts the user to input an "application" by providing the StudentID and JobID. With the help of jQuery, I am able to notify the user if the student or job entered does not exist, if the application is alr ...