javascript - 为选定的单选按钮 div 添加类名称

标签 javascript jquery function parent-child addclass

<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');
});

Example fiddle

关于javascript - 为选定的单选按钮 div 添加类名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31939646/

相关文章:

javascript - 使用 javascript 操作日期对象

javascript - 按类名称删除表行 - Javascript

jquery克隆似乎没有保留可拖动/可放置事件

javascript - 从函数创建动态弹出窗口

javascript - 我如何更好地重新排序我的 javascript 代码?

function - 有没有办法评估一个函数作为匹配臂的输入?

javascript - 将字符串更改为 javascript 中的函数(不是 eval)

javascript - Underscore.js - 将键/值对数组映射到对象 - 一个衬里

javascript - OpenLayers 2 : Unexpected results from Point. 距离()

javascript - 通过ajax传递canvas数据