I have textbox inside the gridview. My requirement is to restrict the input of the textbox into 'X' or 'O' only nothing else. But I am quite new in javascript. Can anyone please tell me how I can achieve that. I would like to mention that I have used Vb.Net and Asp.Net to develop the system. Thanks in advance for your help.
-
1If the input will only be 1 of 2 possible values, why not just use a checkbox instead?ElGavilan– ElGavilan2013-10-30 15:47:44 +00:00Commented Oct 30, 2013 at 15:47
-
Take a look at msdn.microsoft.com/en-us/library/debza5t0(v=vs.100).aspxComfortably Numb– Comfortably Numb2013-10-30 15:49:00 +00:00Commented Oct 30, 2013 at 15:49
-
1+1 to @ElGavilan's idea, or if you wanted to be more transparent to what the user is selecting, use a dropdown. the use of a textbox is not appropriate here.PlantTheIdea– PlantTheIdea2013-10-30 15:49:00 +00:00Commented Oct 30, 2013 at 15:49
-
Thanks for your comment. Actually my client requirement is 'X' or 'O' as input. so, is there any possible solution please?barsan– barsan2013-10-30 15:49:51 +00:00Commented Oct 30, 2013 at 15:49
-
You can use jqueryvalidation.org . Here you can create custom rules for form validation like in your case input can be restricted to certain valuesammu– ammu2013-10-30 16:02:55 +00:00Commented Oct 30, 2013 at 16:02
4 Answers
Here's a jQuery solution if you need to use inputs instead of checkboxes:
$(document).ready(function() {
jQuery('#restricted-input').on('keydown', function(event) {
// reset input
var input = jQuery(this).val('');
// code 88 = x
// code 79 = o
// code 8 = Backspace
if (event.keyCode == 88 || event.keyCode == 79 || event.keyCode == 8) {
// let input happen
} else {
event.preventDefault();
}
});
});
Comments
Thank you everyone for your helpful suggestion to my problem. But here is how I have solved it just now.
This is my Textbox inside the gridview:
<asp:TextBox ID="txtAttend" runat="server" BackColor="Control" MaxLength="1"
EnableViewState="true" Width="15px" onkeyup="ValidateText(this);"></asp:TextBox>
Here, I am calling the ValidateText(this) javascript function.
And here is the function:
<script type="text/javascript" language="javascript">
function ValidateText(i)
{
if(i.value != "X" || i.value != "O")
{
alert("Please Enter 'X' for Present or 'O' for Absent");
}
}
</script>
I got the hint for this solution from this link: TextBox inside GridView validation
Thanks.
Comments
Please see following code that help you to allow only two characters to input. This code will restrict other key strokes and allow only 'X' and 'O'. For demo please see : http://jsfiddle.net/BhaveshKachhadiya/uNfP2/7/
function validate(evt)
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
// alert(charCode);
if (charCode == 120 || charCode== 88 || charCode==111 || charCode==79 || charCode == 8) {
return true;
}
else
{
alert("Please Enter 'X' for Present or 'O' for Absent");
return false;
}
}