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

时间:2013-07-01 12:41:44

标签: javascript jquery forms

我正在尝试在我正在处理的表单上设置一些Javascript表单验证。我已经完成了所有的验证工作,但有一件事我一直在做,我似乎无法搞清楚,也无法在网上找到很多文章。

我遇到的挑战是,如果用户想要在文本框中输入“其他”字段,我希望“其他”单选按钮自动进行检查。这是我在那里的代码,显然不适合我。

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

所以我认为我想要做的是:如果OtherTextValue(我的文本框)不是空白,那么去获取我的单选按钮的ID并进行检查/选择。

我在Javascript世界中仍然相当新,但我正在努力学习。

感谢您的帮助。

6 个答案:

答案 0 :(得分:1)

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

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

您可能希望使用其他事件,因为这仅在释放密钥时触发。 Check the documentation

Here's a simple example

答案 1 :(得分:0)

要检查使用prop

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

我没有看到你的代码,所以也许在最后看起来像这样:

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

答案 2 :(得分:0)

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

通常在单击“其他”单选按钮时,启用textBox。,但您的想法似乎有所不同。请做更多的研究。

答案 3 :(得分:0)

如果你想在没有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;
    }
}

希望有所帮助

答案 4 :(得分:0)

使用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;
   }

答案 5 :(得分:-1)

$(document).ready(function(){
    $('#sourcetext').on('click', function() {
        $('#sourcecheck').prop('checked', true);
    });
});