I am trying to setup some Javascript form validation on a form that I am working on. I have all of the validation working, but one thing I have been tasked with doing I can't seem to figure out and can't find many articles online about it.
The challenge that I have is that if a user wants to type in the "Other" field on a text box I want the "Other" radio button to automatically get checked. Here's the code I had in there that obviously isn't working for me.
if (f.OtherTextValue.value !== '')
{
document.getElementById("OtherTextRadio").checked = true;
return false;
}
So what I think I am trying to do is this: If the OtherTextValue (my text box) is not blank then go get the ID of my Radio button and make it checked/selected.
I am still fairly new in the world of Javascript, but am trying to learn.
Thank you for your help.
Bind an event handler to the text
element, and then set the state of the checkbox
according to whether there is a value or not:
$('#OtherTextValue').on('keyup', function() {
$('#OtherTextRadio').prop('checked', !!this.value.length);
});
You may want to use additional events, as this only triggers when a key is released. Check the documentation
Here's a simple example
To check use prop
:
$('#OtherTextRadio').prop('checked', true);
I dont see your code so maybe in final shoud look like this:
if($('#OtherTextValue').val() == "Other") {
$('#OtherTextRadio').prop('checked', true);
}
$(document).ready(function(){
if ($('#OtherTextValue').val('Other'))) {
$('#OtherTextRadio').prop('checked', true);
}
});
Usually on clicking the "Other" radio button, enable the textBox., but yours idea seems to be different. Please do more research.
If you want to do this without JQuery, as your code in the question suggests, I have mocked up something in JSFiddle that might help:
http://jsfiddle.net/xAcbm/
The key here is to link your check to an event, in this example I've added a simple button:
<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>
The Javascript is:
function checkOther()
{
if (document.getElementById('txtOther').value!='')
{
alert('Value in the box');
document.getElementById('chkOther').checked=1;
}
}
Hope that helps
use onchange event
<asp:radiobutton ID="OtherTextRadio" runat="server"></asp:radiobutton>
<asp:TextBox ID="TextBox1" runat="server" onchange="checkRadio();" ></asp:TextBox>
script is given below
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);
});
});