0

我在 html 中有一个输入文本框,我想只允许用户输入“Y”或“N”,如果他尝试输入任何其他字符,那么它应该显示一个警告对话框。所以有人可以帮我进入dis吗?

4

5 回答 5

2

jQuery版本

$('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();                   
    }

});

检查它在 jsfiddle http://jsfiddle.net/TTgKF/

内联 javascript 版本

<input id="keypress" onkeypress="return allowYN( this, event );" />

和 allowYN 定义为

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

您可以为 Delete 键 ( 46 )、Backspace 键 ( 8 )添加例外。

于 2013-03-30T06:51:29.900 回答
0

假设您能够通过 ID 获取 HTML 元素,这将检查 #myInput 元素并且只接受 Y 或 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!");
}
于 2013-03-30T06:49:00.377 回答
0
<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>
于 2013-03-30T06:56:14.773 回答
0

如前所述,最好的选择是使用单选按钮:

<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>
于 2013-03-30T07:00:26.257 回答
0

you could also try this

 $("input").live('keypress', function(e) {
     if!( code == 89 || code == 121 || 
            code == 78 || code == 110 ) )  { 
            e.preventDefault();
            }
        else //your code
于 2013-03-30T07:07:01.450 回答