table 中有多个记录时在 JS 中获取隐藏值的问题(Coldfusion)

Problem with getting a hidden value in JS when there are multiple records in table (Coldfusion)

这是我的 table,我有此列让用户选择预测时间。

<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>

然后我有 JS 代码(试图获取用户选择的时间和该记录的 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);
                    });
          });
        });

以及 horaPrevista-update-database.cfc 组件:

<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>

问题是当我在table上有多条记录时,它总是更新第一条记录,因为JS获取的隐藏字段id总是第一条记录的id。我在这里做错了什么? 谢谢。

您没有在隐藏元素上使用唯一 ID,因此当您 select 有多个隐藏元素时,JS 将不知道您指的是哪个,它只会使用它看到的第一个元素.

在这种情况下,使用数据属性比使用隐藏字段更容易提供信息。

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

那么你可以这样做:

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