根据“是/否”显示/隐藏文本框

show/hide textbox based on yes/no

本文关键字:隐藏 文本 显示 根据      更新时间:2023-09-26

我有一个调查,30+是/否问题(单选按钮); 如果选择否,则显示文本框以给出原因,如果选择否,则此文本框是必需的。我不能一个接一个地做。如何使用通配符和循环来执行此操作。

<tr>
    <td>1</td>
    <td width="600px">question 1?</td>
    <td width="65px">
        <asp:RadioButton ID="rdM1Y" runat="server" Text="Yes" GroupName="rdM1" />
        <asp:RadioButton ID="rdM1N" runat="server" Text="No" GroupName="rdM1" />
    </td>
    <td><asp:TextBox ID="txtCM1" runat="server" /></td>
</tr>
<tr>
    <td>2</td>
    <td width="600px">question 2?</td>
    <td width="65px">
        <asp:RadioButton ID="rdM2Y" runat="server" Text="Yes" GroupName="rdM2" />
        <asp:RadioButton ID="rdM2N" runat="server" Text="No" GroupName="rdM2" />
    </td>
    <td><asp:TextBox ID="txtCM2" runat="server" /></td>
</tr> 

我需要验证这些文本框是否是必需的,如果他们选择否

好的,所以:

包括jQuery(使它变得更容易):

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

为所有"NO"单选按钮添加radNo类:

<asp:RadioButton class="radNo" ID="rdM2N" runat="server" Text="No" GroupName="rdM2" />

为所有文本框添加txtNo类:

<asp:TextBox class="txtNo" ID="txtCM2" runat="server" />

添加脚本:

<script type="text/javascript">
$(function(){
    $('.radNo').click(function(){
        var c = $(this).is(':checked');
        $(this).parents('tr').find('txtNo').toggle(c);
        if (c) {
            $(this).parents('tr').find('txtNo').focus();
        }
    });
    // validate that there's text if select NO
    $('.txtNo').bind('blur', function(){
        if ($(this).val().length < 1) {
            $(this).focus(); 
            alert('please provide a reason');
        }
    });       
});
</script>

应该可以做到,希望我理解得很好,这很有帮助。

生成的HTML - 请注意,textarea ID 等于radio按钮名称

<table>
    <tr>
    <td>1</td>
    <td width="600px">question 1?</td>
    <td width="65px">
        <label><input type="radio" name="rdM1" /> Yes</label>
        <label><input type="radio" name="rdM1" class="give_reason" /> No</label>
    </td>
    <td><textarea id="rdM1" name="rdM1-reason"></textarea></td>
</tr>
</table>

.CSS

textarea {display: none;}

爪哇语

$(document).on('click', 'input:radio', function(){
   el = $('#' + this.name); 
   ($(this).hasClass('give_reason'))? el.show() : el.hide(); 
});

演示

首先给no-radiobutton一个公共类,例如说"noRadio"。然后,您可以使用此类收听所有单选按钮的单击事件。在事件处理程序函数中,您可以找到相应的文本框并显示它。我的示例代码如下:

$(".noRadio").click(function(e) {
    // get id of the clicked radio button
    var id = $(e.target).attr("id");
    // remove "rdM" and "N" from id and get pure question number
    id = id.replace("rdM", "").replace("N", "");
    // select the corresponding text box by its id, e.g. "#txtCM2" if "#rdM2N" selected
    $("#txtCM" + id).show();
});

我在我的项目中尝试了这种方法,它有效。

$(document).on('click', 'input:radio', function(){
$('table').each(function(){
if($('input[type= radio]:checked').val() == no)) 
{
    $('textbox').show();
}
});
  });