使用jQuery禁用表单元素 循环生成多组元素仅首组生效问题求助
问题根因
- 重复ID:HTML规范要求页面ID唯一,你用cfoutput循环生成了6组完全相同id的
prods、test、trgt元素,jQuery选择器$('#prods')只会匹配页面第一个符合的元素,事件也只会绑定到第一个输入框,取值也只会取第一个元素的内容,这是核心问题。 - 逻辑偏差:你原有代码里
calc<70的时候给下拉加disabled属性,和“小于目标值70%启用下拉”的需求完全相反。 - 节点结构问题:隐藏的目标值字段放在
control-group外面,同组关联查找不方便。
修复步骤
第一步:修改ColdFusion渲染代码
调整节点结构,给元素加唯一ID、公共类名,方便关联查找:
<cfquery datasource="#request.dsn#" name="getProdInfo"> Select * from dbo.Lines,dbo.[Shift],dbo.operations where lineID=#form.SELLINE# and ShiftID=#form.SELSHIFT# </cfquery> <cfoutput query="getProdInfo"> <!-- 把隐藏字段也放到control-group里,方便同组查找 --> <div class="control-group"> <label for="Ops_#CurrentRow#">#OperationName# </label> <!-- 加公共类prod-input,唯一id带查询行号 --> <input class="input-xlarge focused prod-input" id="prods_#CurrentRow#" name="prod" placeholder="Enter Production" type="number" validate="integer" /> <!-- 加公共类test-select,唯一id带查询行号,默认禁用 --> <select class="test-select" name="Test" id="test_#CurrentRow#" disabled> <option>Option1</option> <option >Option2</option> </select> <!-- 加公共类target-val,唯一id带查询行号,设置为隐藏字段 --> <input class="input-small focused target-val" id="trgt_#CurrentRow#" name="Target" value="580" type="hidden"> </div> </cfoutput>
这里用到了cfquery循环自带的CurrentRow变量,会自动生成1-6的行号,保证所有元素id唯一。
第二步:修改jQuery逻辑代码
用事件委托绑定所有输入框的事件,通过当前触发元素查找同组的对应节点:
<script type="application/javascript"> // 给所有.prod-input绑定focusout事件 $(document).on('focusout', '.prod-input', function(){ // 获取当前触发事件的输入框所在的control-group容器 const $group = $(this).closest('.control-group'); // 从当前容器里找对应的值,不依赖全局id const prodVal = parseFloat($(this).val()) || 0; const targetVal = parseFloat($group.find('.target-val').val()) || 1; // 避免除以0异常 const calc = (prodVal / targetVal) * 100; // 按需求实现:小于70%启用,否则禁用 if (calc < 70) { $group.find('.test-select').removeAttr('disabled'); } else { $group.find('.test-select').attr('disabled', 'disabled'); } }); </script>
修复说明
- 用类名做事件绑定,不受ID重复影响,后续新增/删除表单组不需要修改JS代码
- 通过
closest()查找当前输入框的父容器,再从容器内查找同组的下拉和目标值,完全避免跨组取值的问题 - 增加了默认值避免空输入、除以0的异常
- 修正了原有逻辑和需求相反的问题
内容的提问来源于stack exchange,提问作者Tayyab Hussain
相关产品推荐
相关产品推荐

