如果我选择第一个(第二个或最后一个)选项,则其余选项将被禁用,并且所选选项中的所有值将被启用。但是,我的代码工作方向错误。请帮我解决这个问题。
HTML:
<table>
<tr>
<td>
<input type="radio" name="vehicle" value="company_vehicle" />Company Vehicle</td>
</tr>
<tr class="set_width" id="company_vehicle">
<td>
<input type="text" />
</td>
<td>
<input type="checkbox" />Company Vehicle</td>
</tr>
<tr>
<td>
<input type="radio" name="vehicle" value="hiring_vehicle" />Hiring Vehicle</td>
</tr>
<tr class="set_width" id="hiring_vehicle">
<td>
<input type="text" />
</td>
<td>
<input type="radio" name="abc" value="car" />Car</td>
<td>
<input type="radio" name="abc" value="bus" />Bus</td>
</tr>
<tr>
<td>
<input type="radio" name="vehicle" value="taxi" />Taxi</td>
</tr>
<tr class="set_width" id="taxi">
<td>
<input type="checkbox" />Taxi</td>
</tr>
</table>
Javascript:
var rbt_vehicle = $("input[name=vehicle]");
$(rbt_vehicle).on('change', function (e) {
var optionSelected = $("option:checked", this);
var valueSelected = this.value;
//alert(valueSelected);
$("#" + valueSelected).find('input[type="text"]').val('').addClass("readOnly").attr('disabled', true);
$("#" + valueSelected).find(':checkbox,:radio').prop('checked', false).addClass("readOnly").attr('disabled', true);
});
最佳答案
你可以这样做:
var rbt_vehicle = $("input[name=vehicle]");
$(rbt_vehicle).on('change', function (e) {
var valueSelected = this.value;
$('#' + valueSelected).find(':text').prop('disabled', false).val('').removeClass('readonly').closest('tr').siblings('tr.set_width').find(':text').prop('disabled', true).addClass('readonly');
$('#' + valueSelected).find(':checkbox,:radio').prop('disabled', false).closest('tr').siblings('tr.set_width').find(':checkbox,:radio').prop('disabled', true);
});
请注意,您需要使用.prop()
而不是.attr()
来设置表单元素的状态。
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
<强> Updated Fiddle
关于javascript - 如何使用 Javascript 重置单选按钮中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23558644/