简体   繁体   中英

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. 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.

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. 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

 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

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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