这是我的表格,其中有一列可让用户选择预测时间。
<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>
问题是当我表上有多条记录时,它总是更新第一条记录,因为JS获取的隐藏字段id始终是第一条记录的id。我在这里做错了什么? 谢谢。
最佳答案
您没有在隐藏元素上使用唯一的 ID,因此当您选择隐藏元素时,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);
关于javascript - 当表中有多个记录时,在 JS 中获取隐藏值时出现问题(Coldfusion),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129335/