繁体   English   中英

从输入框中删除所有空格,es6

[英]Removing all white space from an input box, es6

当用户在输入框中输入内容时,我试图删除任何空格。 我一开始尝试使用三种不同的方法:粘贴文本时删除空格的正则表达式,按下空格键时删除空格的正则表达式,以及简单的修剪。 注意:我需要使用类来调用方法。 不知道从哪里开始......我很感激你的帮助!

 (function () { class Digit { // when user enters keys, do not allow spaces method2(userInput) { console.log({userInput}); console.log("formatInput"); const input = userInput.target.value; console.log(input.length); if (!input.length) return; if (userInput.which === 32) { // 32 is space key console.log("this is a space"); userInput.value = this.method1(); } } method1() { console.log("trimthis input"); return userInput.trim(); } // when user pastes input remove spaces method3() { console.log("formatPaste"); const reg = new RegExp(/\\s+/, ""); console.log(this.userInput); return this.userInput.replace(reg, ""); } } const userInput = document.querySelector("#inputNumber"); console.log("User inputs", {userInput}); const digitObject = new Digit(); console.log(digitObject); userInput.addEventListener("keyup", function() { digitObject.method2(); }, false); digitObject.method3(); }());
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Numbers App</title> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto:400,500" rel="stylesheet"> <!-- CSS --> <link rel="stylesheet" href="style.css"> </head> <body> <!-- ASSIGNMENT: create page where user can type/save numbers only, css grid --> <div class="wrapper"> <!-- simple form with number input and submit function, auto trim spaces --> <form> <div class="form"> <div> <input class="input--number has-float-label go-bottom Digit" id="inputNumber" placeholder="Enter Number" type="text" required /> <label for="inputNumber">Input</label> </div> <div class="btn--group"> <input type="button" value="Post" class="btn post" title="Post"> <input type="button" value="Clear" class="btn clear" title="Clear"> </div> </div> </form> <!-- saved numbers table with date submitted --> <!----> </div> <!-- end wrapper --> <!-- footer --> <!-- Javascript --> <script src="script.js"></script> </body> </html>

使用事件input来捕获各种变化和以下正则表达式/ /g

 document.getElementById('textfield').addEventListener('input', function() { this.value = this.value.replace(/ /g, ''); });
 <input id='textfield'>

暂无
暂无

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

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