我有一个表单,可以使用 jquery 添加新行来增加表单元素。在该表单中,我有两个下拉选项(名称:类型和帐户)
和两个文本输入(名称:debit_amount 和credit_amount)
。
问题:
我开发了一个 jquery 代码来根据下拉选项中选定的值启用/禁用文本输入。但只有当我不添加新行时,代码才能正常工作。如果我添加一个新行,它仅适用于第一行,我的意思是它仅禁用/启用第一行的输入。
为了清楚起见,我没有提供下面添加新行的代码,但要获得所有代码的实时图片,请检查此链接,jsfiddle.net
您能否告诉我应该在代码中进行哪些更改才能根据所选值禁用/启用所有输入(包括生成的行的输入)?
我的 HTML
<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>
<table class="dynatable">
<thead>
<tr>
<th>Type</th>
<th>Account Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
</thead>
<tbody id="p_scents">
<tr>
<td>
<select name="type" id="type">
<option value="Debit">Debit</option>
<option value="Credit">Credit</option>
</select>
</td>
<td>
<select name="accounts" id="accounts">
<option value="">SELECT</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
</td>
<td>
<input type="text" name="debit_amount" id="debit_amount" />
</td>
<td>
<input type="text" name="credit_amount" id="credit_amount"/>
</td>
</tr>
</tbody>
禁用/启用的条件
1. 如果选择类型 == 借方并选择帐户中的值,则启用借方金额输入并禁用贷方金额输入
2. 如果选择类型 == Credit 并选择帐户中的值,则启用 Credit_amount 输入并禁用 debit_amount 输入
3.如果未选择类型和帐户的任何值,则禁用两者
我的 Jquery 代码,用于根据下拉值禁用/启用输入
//ON the change of accounts(dropdown select)
$("#accounts").change(function() {
var type = $("select#type").val();
var accounts = $("select#accounts").val();
if (type == "Debit") {
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit") {
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
if (accounts == "") {
$('input[name=credit_amount]').val('');
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').attr("disabled", true);
}
});
//ON the change of type(dropdown select)
$("#type").change(function() {
var accounts = $("select#accounts").val();
var type = $("select#type").val();
if (type == "Debit" && accounts != '') {
$('input[name=credit_amount]').val('');
$('#credit_amount').attr("disabled", true);
$('#debit_amount').removeAttr("disabled", true);
}
if (type == "Credit" && accounts != '') {
$('input[name=debit_amount]').val('');
$('#debit_amount').attr("disabled", true);
$('#credit_amount').removeAttr("disabled", true);
}
});
最佳答案
问题是您的输入元素都具有相同的 id 属性值,即:“debit_amount”和“credit_amount”,因此 jQuery 不知道“#debit_amount”和“#credit_amount”选择器引用的是哪一个。
元素 ID 在页面中应该是唯一的,因此您应该在每个元素的末尾附加一个序列号,例如:
<select name="accounts_1" id="accounts_1">
....
<input type="text" name="debit_amount_1" id="debit_amount_1" />
<input type="text" name="credit_amount_1" id="credit_amount_1" />
两种解决方案:
- 使用 jQuery 遍历 API 查找与触发 onChange 事件的 select 元素相关的 input 元素。这是很脆弱的,如果你改变你的标记太多,就会崩溃
- 从
关于javascript - Jquery:根据下拉列表的值启用/禁用对于动态生成的输入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11469749/