<div>
One : <input type="radio" name="typeof" id="typeof1-grey" value="grey" />
Two : <input type="radio" name="typeof" id="typeof2-pink" value="pink" />
Three : <input type="radio" name="typeof" id="typeof3-green" value="green" />
<div>
<div id="one" style="display:none;">
ABC : <input type="text" name="abc" value="" />
PQR : <input type="text" name="pqr" value="" />
</div>
<div id="two" style="display:none;">
XYZ : <input type="text" name="xyz" value="" />
</div>
<div id="three" style="display:none;">
Full Name: <input type="text" name="fname" value="" />
</div>
如果选择“One”(灰色)单选按钮,我需要显示 DIV id“one”并将类名(必需)添加到 div 中的所有输入字段。 同样,如果我更改为粉红色单选按钮,则删除以前的 div 类名称并使用 Jquery 添加到 DIV id 2 中。
请帮助我!
最佳答案
您可以通过单选控件的索引
将其与div
关联起来。然后您可以根据需要添加/删除类。试试这个:
$('input[type="radio"]').change(function() {
$('input[type="text"]').removeClass('required');
$('div').not(':first').hide();
$('div').eq($(this).index() + 1).show().find('input').addClass('required');
});
请注意,您可以通过在 HTML 中使用类来简化此逻辑:
<div>
One : <input type="radio" name="typeof" id="typeof1-grey" class="radio" value="grey" />
Two : <input type="radio" name="typeof" id="typeof2-pink" class="radio" value="pink" />
Three : <input type="radio" name="typeof" id="typeof3-green" class="radio" value="green" />
<div>
<div id="one" class="optional-div">
ABC : <input type="text" name="abc" value="" class="text-input" />
PQR : <input type="text" name="pqr" value="" class="text-input" />
</div>
<div id="two" class="optional-div">
XYZ : <input type="text" name="xyz" value="" class="text-input" />
</div>
<div id="three" class="optional-div">
Full Name: <input type="text" name="fname" value="" class="text-input" />
</div>
$('.radio').change(function() {
$('.text-input').removeClass('required');
$('.optional-div').hide().eq($(this).index()).show().find('.text-input').addClass('required');
});
关于javascript - 为选定的单选按钮 div 添加类名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31939646/