如何在选择单选按钮时清除文本字段中的文本

How to clear text inside text field when radio button is select

本文关键字:文本 字段 清除 选择 单选按钮      更新时间:2023-09-26

目前我有这个单选按钮

  1. 电子学
  2. 计算机
  3. 别人

我正在尝试做的是,如果选择了单选按钮Others,我想显示一个输入文本字段并让用户键入。

我想做的是,当我选择Others并在输入字段中键入内容时,然后当我选择返回EletronicsComputers时,我想清除我在输入字段中编写的文本。

请为我提供JavaScript或jQuery的解决方案。

这是我的代码示例。请检查一下:http://jsfiddle.net/dnGKM/

更新

$('input:radio').on('click', function() {
    if($(this).attr('id') == 'others') {
        $('#showhide').css('opacity', 1.0);
   } else {
       $('#showhide').css('opacity', 0).find('input:text#others_text').val('');
    }  
});​

演示

你可以使用这个:

document.getElementById("others_text").value='';

以清除输入字段。

请在您的代码中添加以下代码:

document.getElementById("others_text").value = '';

现在它看起来像:

document.getElementById("others").addEventListener("click", function()
{
    document.getElementById("others_text").value = '';
    document.getElementById("showhide").style.opacity = 1;
}, false);
document.getElementById("computers").addEventListener("click", function()
{
    document.getElementById("showhide").style.opacity = 0;
}, false);
document.getElementById("electronics").addEventListener("click", function()
{
    document.getElementById("showhide").style.opacity = 0;
}, false);​

这将对您有所帮助。

尝试使用此解决方案:

$(function() {
      $('input[type="radio"]').click(function() {
       if($(this).attr('id') == 'others') {
           $('#others-text').show();
       } else {
           $('#others-text').hide();
           $('#others-text').val('');
       }
   });
})

这里有一个JSFiddle链接:

http://jsfiddle.net/dnGKM/4/

您将jQuery标签添加到您的问题中,因此应该使用 jQuery :)

.CSS:

.hidden {
    display: none;
}

.HTML:

<label for="electronics">Electronics</label>
<input type="radio" id="electronics" name="rdbutton" />
<label for="computers">Computers</label>
<input type="radio" id="computers" name="rdbutton" />
<label for="others">Others</label>
<input type="radio" id="others" name="rdbutton" />
<input type="text" id="others-text" name="others-text" class="hidden" />

.JS:

$(function() {
    $('input[type="radio"]').click(function() {
        if($(this).attr('id') == 'others') {
            $('#others-text').removeClass('hidden');
        } else {
            $('#others-text').addClass('hidden');
            $('#others-text').val('');
        }
    });
});

===

============HTML
<input type="radio" name="rdo" value="1" checked="checked" />Electronics
<input type="radio" name="rdo" value="2" />Computers
<input type="radio" name="rdo" value="3" />Others

====

=============j查询
  $('input[name=rdo]').change(function() {
         var a = $(this).val();
         if (a != 3) {
             $('#textboxid').hide();
         }else{
             $('#textboxid').val('');
             $('#textboxid').show();
         }
   });
$("#<%=text1.ClientID%>").val('');