I am trying to develop a braces auto completion feature in a text box. I tried the javascript replace function on the textbox. But i am getting a weird output from the function. Here's the code i am work on.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type ="text" id="textbox">
</body>
</html>
Javascript:
var element = document.getElementById('textbox');
element.oninput = function(){
var code = (function(){
var val = element.value;
element.value = val.replace(/\{/ , "{}");
})();
};
When i type a single {
brace i am getting {}
, when i type more than 1 i am getting {}}}{{
and it goes on .. sometimes my browser freezes when i try to clear the braces.
Here's the js bin link JSBIN
The problem is that you are always replacing {
with {}
, even if the bracket has already been matched. You should instead ensure it was not with negative lookahead: /\{(?!\})/
onkeyup
and add a guard clause. Expanding on @Andi's idea, I also added exclusion for the arrow keys so you won't be forced to the end of the textbox when you want to navigate through the text:
var element = document.getElementById('textbox');
element.onkeyup = function(){
if([8, 37, 39].indexOf(event.which) != -1)
return false;
var code = (function(){
var val = element.value;
element.value = val.replace(/\{(?!\})/g, "{}");
})();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With