简体   繁体   English

限制输入只接受括号,不接受字母或数字

[英]Limit input to only accept parentheses, not letters or numbers

It should only accept parentheses inside the input.它应该只接受输入中的括号。 It should not accept letters or numbers它不应该接受字母或数字

 function brackets() { var inp = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inp,result) var l = 0; var r = 0; for (var i = 0; i < inp.length; i++) { if (inp[i] === "(") { l++; } else if (inp[i] === ")") { r++; } } console.log(l,r) if (l == r) { document.getElementById("strong").innerHTML = "Matched"; } else if (l !== r) { document.getElementById("strong").innerHTML = "Not matched"; } } document.getElementById("input").addEventListener("input",brackets);
 <input type="text" id="input" /> <span id="strong"></span>

Explanation : I have used keydown event handler.说明:我使用了keydown事件处理程序。 Whenever the key is pressed, it checks if it's a paranthesis or not.每当按键被按下时,它会检查它是否是一个括号 I case it's not, the input does not gets entered inside the input element.我的情况不是,输入不会被输入到input元素中。

Doing this will avoid input of character, checking if it's not a parenthesis, and removing it if it's not:这样做将避免输入字符,检查它是否不是括号,如果不是,则将其删除:

 document.getElementById("input").addEventListener("keydown", function(event) { if (!(event.shiftKey && (event.key == ")" || event.key == "("))) { event.preventDefault(); } });
 <input type="text" id="input" />

What you can do is add onchange event listener to the input.您可以做的是将 onchange 事件侦听器添加到输入中。 Then when a user types on the input, you can validate the input to be either "(" or ")" otherwise you clear the input box然后当用户在输入上键入时,您可以验证输入为“(”或“)”,否则清除输入框

Do it by checking if the character typed is a parenthesis, and if not, slice the last character.通过检查输入的字符是否是括号来完成,如果不是,则对最后一个字符进行切片。

slice() Docs slice()文档

 function brackets() { var inp = document.getElementById("input"); if (inp.value.slice(-1) != '(' && inp.value.slice(-1) != ')') { inp.value = inp.value.slice(0, -1); } }
 <input type="text" oninput="brackets()" id="input"/>

Try this:尝试这个:

 let inp = document.getElementById('input'); var result = ""; inp.addEventListener('keyup', (e) => { if(inp.value[inp.value.length - 1] === '(' || inp.value[inp.value.length - 1] === ')'){ result += inp.value[inp.value.length - 1] } console.log(result) return result })
 <input id="input">

First, I suggest using regexp and the pattern attribute.首先,我建议使用正则表达式和模式属性。 https://www.w3schools.com/tags/att_input_pattern.asp https://www.w3schools.com/tags/att_input_pattern.asp

 input:invalid { border: red solid 3px; }
 <!DOCTYPE html> <html> <head> </head> <body> <p>An input that CANNOT contain parenthesis</p> <input type="search" id="search" name="search" pattern="[^()]+" title="Invalid input"> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM