选中文本框时激活单选按钮

Activate radiobutton when text box is selected

本文关键字:激活 单选按钮 中文 文本      更新时间:2023-09-26

我正试图在我正在处理的表单上设置一些Javascript表单验证。我已经完成了所有的验证,但有一件事我一直在做,我似乎搞不清楚,也找不到很多关于它的在线文章。

我面临的挑战是,如果用户想在文本框上键入"其他"字段,我希望"其他"单选按钮自动被选中。这是我在那里的代码,显然对我不起作用。

if (f.OtherTextValue.value !== '')
{
    document.getElementById("OtherTextRadio").checked = true;
    return false;
}

所以我想我要做的是:如果OtherTextValue(我的文本框)不是空的,那么去获取我的Radio按钮的ID并选中它。

我对Javascript的世界还很陌生,但我正在努力学习。

谢谢你的帮助。

将事件处理程序绑定到text元素,然后根据是否有值设置checkbox的状态:

$('#OtherTextValue').on('keyup', function() {
  $('#OtherTextRadio').prop('checked', !!this.value.length);
});

您可能需要使用其他事件,因为这只会在释放密钥时触发。检查文件

下面是一个简单的例子

要检查,请使用prop:

$('#OtherTextRadio').prop('checked', true);

我看不到你的代码,所以也许在最后应该是这样的:

if($('#OtherTextValue').val() == "Other") {
    $('#OtherTextRadio').prop('checked', true);
}
$(document).ready(function(){
 if ($('#OtherTextValue').val('Other'))) {
    $('#OtherTextRadio').prop('checked', true);   
  }
});

通常单击"其他"单选按钮,启用文本框。,但你的想法似乎不一样。请多做研究。

如果你想在没有JQuery的情况下完成这项工作,正如你在问题中的代码所建议的那样,我在JSFiddle中模拟了一些可能会有所帮助的东西:http://jsfiddle.net/xAcbm/

这里的关键是将您的支票链接到一个事件,在这个例子中,我添加了一个简单的按钮:

<input type="radio" id="chlVal" name="selVal" value="Val 1"/>Value 1<br/>
<input type="radio" id="chkOther" name="selVal" value="Other"/>Other<br/>
<input type="text" id="txtOther">
<button id="btn" onclick="Javascript: checkOther()">Check Form</button>

Javascript是:

function checkOther()
{
    if (document.getElementById('txtOther').value!='')
    {
        alert('Value in the box');
        document.getElementById('chkOther').checked=1;
    }
}

希望对有所帮助

使用onchange事件

<asp:radiobutton ID="OtherTextRadio" runat="server"></asp:radiobutton>
<asp:TextBox ID="TextBox1" runat="server" onchange="checkRadio();" ></asp:TextBox>

下面给出了脚本

   function checkRadio() {
       if (document.getElementById("TextBox1").value != "") {
           document.getElementById("OtherTextRadio").checked = true;
       }
       else document.getElementById("OtherTextRadio").checked = false;
   }
$(document).ready(function(){
    $('#sourcetext').on('click', function() {
        $('#sourcecheck').prop('checked', true);
    });
});