Having trouble retrieving a hidden value in JavaScript when dealing with multiple records in a Coldfusion table

In this table, there is a column that allows users to select a predicted time.

<cfoutput query="getReservations">
       <tbody>
        <td><input class="form-control predicted" name="predicted" id="ReservaTempoPrevisto" placeholder="HH:MM" value="#timeFormat(ReservaTempoPrevisto,'HH:mm')#">
          <input type="hidden" name="id" class="id" value="#ReservaID#"></td>

Next, the JavaScript code is used to capture the user's selected time and record ID:

//Update the predicted time
        $(document).ready(function() {
           $(".predicted").on("change",function(event){
                var hora = this.value;
                console.log("Updating time = "+ hora);
                var id = jQuery('input[type=hidden][name=id]').val();
                console.log(id);
                $.ajax({
                        url: "horaPrevista-update-database.cfc"
                        , type: "POST"
                        , dataType: "json"
                        , data: {"method" : "updatePredicted", "returnFormat": "json", "hora": hora, "id": id}
                    }).done(function(response) {
                        console.log("response", response);
                    }).fail(function(jqXHR, textStatus, errorMessage) {
                       console.log("errorMessage",errorMessage);
                    });
          });
        });

Lastly, the horaPrevista-update-database.cfc component is presented for updating the database:

<cfcomponent>   
<cfset variables.dsn = "listareservas">

<cffunction name="updatePredicted" returntype="struct" access="remote">
   <cfargument name="hora" type="string" required="true">
   <cfargument name="id" type="numeric" required="true">

   <cfset local.response = {success=true}>

   <cftry>
       <cfquery datasource="#variables.dsn#">
           UPDATE Reservas
           SET    ReservaTempoPrevisto = <cfqueryparam cfsqltype="cf_sql_timestamp" value="#arguments.hora#"> 
           WHERE  ReservaID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.id#">
       </cfquery>
       <cfcatch>    
           <!--- add handling here... --->
           <cfset local.response = {success=false}>
       </cfcatch>
   </cftry>

   <cfreturn local.response>
</cffunction>

If multiple records are present in the table, the issue arises as it always updates the first record. This happens because the hidden field ID retrieved by the JavaScript is consistently that of the initial record. What could be improved in this setup? Thank you.

Answer №1

Ensure each hidden element has a unique ID to avoid confusion for the JavaScript when selecting from multiple elements. Using data attributes is a simpler solution in this case.

<input class="form-control predicted" name="predicted" id="ReservaTempoPrevisto" placeholder="HH:MM" value="#timeFormat(ReservaTempoPrevisto,'HH:mm')#" data-id="#ReservaID#">

Then you can use:

var hour = this.value;
console.log("Updating time = "+ hour);
var identifier = $(this).data('id');
console.log(identifier);

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

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

Updating lists using PHP and Ajax: a dynamic approach

I am currently using a chat service that relies on polling every 20 seconds for new user data in the chat room. I am looking to improve this process by only downloading information for new users who have just joined, rather than re-downloading old data f ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

What is the trick to displaying Bootstrap 5 dropdown arrows when the button label is lengthy?

Within a fixed-width element, I have a Bootstrap dropdown which causes the arrow to disappear when the button text is too long. Is there a way to trim the text while still displaying the arrow, similar to this image: https://i.sstatic.net/jHp5R.png .ou ...

The browser is not displaying the results from Mongodb, yet they are appearing in the console

I am currently using the following code for my router: let mongoose = require('mongoose'); // connecting with our model let ByProduct = require('../models/Byproduct') router.get('/',(req,res,next)=>{ ByProduct.find().th ...

Issue with Angular ng-model not functioning as expected within ng-repeat block

Encountering an issue when trying to bind Json data into ng-model within ng-repeat. html : <div ng-controller="Ctrl"> <div> <table> <th> <td>add</td> <td>ed ...

Why does serializing a JavaScript Object to JSON result in "{}"?

Hello fellow developers, I'm currently working on setting up a LocalStorage feature for my web application. One issue I've come across is that all objects in the Model abstraction layer need to be serialized. I understand that functions aren&a ...

Employing promises for retrieving ajax data

I've been struggling to make sure my code waits for an ajax call to finish before proceeding, as I need data in an array first. No matter what I try, it seems like promises might be the best solution in this scenario. Currently, the ajax call still oc ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

Error: Attempted to access the 'state' property of an undefined object

I am working with the following function: extractCountries: function() { var newLocales = []; _.forEach(this.props.countries, function(locale) { var monthTemp = Utils.thisMonthTemp(parseFloat(locale["name"]["temperature"])); if(p ...

Leverage the power of the modal component in your ReactJS

I'm facing an issue with the antd library. Even after installing it from the official site and importing the modal component, it's not functioning properly for me. I've carefully checked everything in my code and everything seems to be fine. ...

Difficulty in updating Vue variable value following a request

Hello everyone, I am facing an issue regarding a variable value. Within the request, I am comparing each array value to see if there is a match and then updating the match variable to true if a match is found. However, the problem arises when the updated ...

The comparison between 'typeof error' and 'undefined' reveals that the data is

I am encountering an issue with a piece of code that is generating an error, and I have been unable to find a suitable solution in JavaScript. var data = new FormData(); $.each(files, function(key, obj) { data.append(o ...

Using jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

Challenges arise when employing angular scope functions in the context of the DOM (html)

UPDATE: Encountered an issue caused by attempting to iterate over a function's return value using ng-repeat \ ng-options, rather than converting the data into a regular object through a promise. Here is the code snippet: $scope.layout.getParti ...

CSS compatibility across different browsers

Check out my jsFiddle for an example of an onHover event that changes the image. It's working perfectly in chrome, but not quite right in firefox. Any suggestions on how to fix it? Here's the jQuery function I'm using: $(document).ready(fu ...

What are the differences in how a link tag responds on mobile devices?

I have a question regarding opening a pdf in an iframe on the current page. Is there a way to handle this differently for mobile/tablet users? For example, clicking the link could open it in another tab for better readability instead of within the iframe ...

Investigate the dynamic form validation using jQuery

I have set up an input field using jQuery. When the button "add a step" is clicked, jQuery will generate the following structure in the div all_steps: <div class="step"> <div class="header_step">Step '+ (x + 1) +' of the Tutoria ...