Tuesday, December 4, 2012

Validate textbox based on radio button selection in java script

In this post i will show a simple validation on text box using java script base on radio box selection.Here i have radio button groups which has four radio button.Then the requirement here is ,when we checked the other radio button we should enter the data in to text box.To resolve this just given Id's to both controls and access to through the script.
HTML:
<div>
<table>
<tr>
<td><input type="radio" name="Amt_Num" value="1000"/></td><td>$2,000</td>
</tr>
<tr>
<td><input type="radio" name="Amt_Num" value="500"/></td><td>$300  </td>
</tr>
<tr>
<td><input type="radio" name="Amt_Num" value="450"  /></td><td>$250  </td>
</tr>
<tr>
<td><input type="radio" id="OtherR" name="Amt_Num" value="Other" />
</td><td>Other:</td><td><input type="text" id="OtherT"  name="AmtOther_Num" size="6"/></td>
</tr>
</table>
<input type="submit" id="btnsubmit" value="GetData" onclick="validatetext()"/>
</div>
 
JavaScript:

function validatetext() {
var v = document.getElementById('OtherR');
if (v.checked) {
var t = document.getElementById('OtherT').value;
if (t =="") {
alert('Please enter value in Other');
document.getElementById('OtherT').focus();
} 
}
}
In the above script ,just check the text box data is empty or not.If the text box is empty ,we will display an alert for confirmation.

No comments:

Bel