i have a input textbox in html and i want to allow the user just 'Y' or 'N' and if he tries to enter any other character then it should show an alert dialog box. so can anyone help me into dis??
5 Answers
jQuery version
$('input').keypress( function( e ){
$(this).val('');
var code = e.which || e.keyCode ;
if ( !( code == 89 || code == 121 ||
code == 78 || code == 110 ) ){
alert('you entered wrong key');
e.preventDefault();
}
});
check it on jsfiddle http://jsfiddle.net/TTgKF/
inline javascript version
<input id="keypress" onkeypress="return allowYN( this, event );" />
and allowYN define as
function allowYN( el, event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
el.value = '';
isYN = (charCode == 89 || charCode == 121 ||
charCode == 78 || charCode ==110 );
if ( !isYN ) {
alert('you entered wrong key');
}
return isYN;
}
You can add exception for Delete key (46), Backspace key (8) ..
1 Comment
jahroy
A link to the keycode table would be better than providing him codes one key at a time...
Assuming you're able to get the HTML element by ID, this would check the #myInput element and only accept Y or N.
if ((document.getElementById('myInput').value == 'Y') ||
(document.getElementById('myInput').value == 'N')) {
// Do stuff if it's correct.
} else {
alert("You're doing it wrong!");
}
Comments
As previously noted, the best option is to use radio buttons:
<input type="radio" name="yn" value="Y">Y<br>
<input type="radio" name="yn" value="N">N<br>
Then either set one as selected or check on submit that one is selected. Alternatively, you can use scripted input elements, but it is not sensible:
<script>
function validateYN(element) {
var errNode = document.getElementById(element.id + '_err');
if(/^[YN]$/.test(element.value)) {
errNode.innerHTML = '';
} else {
errNode.innerHTML = "You must enter Y or N";
}
}
</script>
Please enter Y or N: <input name="foo" id="foo" onchange="validateYN(this);"
onblur="validateYN(this);">
<span id="foo_err"></span>
Comments
<html>
<head>
<script type="text/javascript">
function keyPressed(evt)
{
var theEvent = evt || window.event;
var k = theEvent.keyCode || theEvent.which;
if(k == 89 || k == 78 || k == 8 || k == 46)
return true;
else{
alert("Your Message");
evt.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeydown="keyPressed(event)" />
</body>
</html>
1 Comment
jahroy
@RobG - Yeah... I guess I knew that was a sketchy, subjective link. Though I thought it was pretty much concensus that inline listeners were bad practice.
.keypress()function for validating this with Javascript. When submitting the form, you will still want to validate the output on your server side as well.element.onkeydown = function() { if (!this.value.trim().match(/(Y|N)/)) alert('nope'); return false;}