This is the sixth day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

1. Remove Spaces from the left and right sides of the string

<h2>Tests to remove whitespace from the left and right sides of a string</h2>
<input type="text" id="strs" value="Need to filter space">
<input type="button" id="rstrsBtn" value="Filter">

<script>
window.onload = function () {
  var _rstrsBtn = document.getElementById("rstrsBtn"),
      _strs = document.getElementById("strs");

  _rstrsBtn.onclick = function () {
    _strs.value = _strs.value.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g.""); }};</script>
Copy the code
  • replace()Is a JavaScript native function, re/^(\s|\u00A0)+|(\s|\u00A0)+$/gIs the key part,\sIs used to match any whitespace character;

2. Verify whether the user has entered the password

Forms often have mandatory fields. For example, when registering a user, you must enter the user name before submitting the registration information. When verifying user input, you usually need to filter and then verify

function (chars) {
  return! chars ?true : false; // The first way
  return chars.length == 0 ? true : false; // The second way
}
Copy the code
<h2>Verify input</h2>
<input type="text" id="strs" value="Need to filter space">
<input type="button" id="isContent" value="Verify null">

<script>
window.onload = function () {
  var _isContent = document.getElementById("isContent"),
      _strs = document.getElementById("strs");

  _isContent.onclick = function () {
    if(! _strs.value.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g."")) {
      alert("Your input is empty!");
    } else {
      alert("Your input is not empty!"); }}};</script>
Copy the code
  • usingreplace()In combination with re to filter null characters, then “!” Symbol determines whether it is null

3. Disable input

Scheme 1: Control input through special attributes of form elements
<input type="text" value="Do not enter" disabled />
<input type="text" value="Do not enter" readonly />
Copy the code
  • disabledProperty cannot match<input type="hidden">Use together;
  • Remove the disabled value through JavaScript;
Option 2: Methods of controlling input via JavaScript (controlling text input or focus via events)
<input type="text" value="Do not enter" id="inhibitingInput" />
Copy the code
window.onload = function () {
 var _inhibitingInput = document.getElementById("inhibitingInput");

 // The first way is to control the loss of focus
 _inhibitingInput.onfocus = function () {
   _inhibitingInput.blur();
 }

 // The second way, using keyup and blur
 var onText = function () {
   _inhibitingInput.value = "";
 }

 _inhibitingInput.onkeyup = _inhibitingInput.onblur = noText

}
Copy the code
  • Compared with method 1, method 2 has many shortcomings, such as a large amount of code, unable to directly prevent text copied and pasted by the mouse, although the content can be cleared when the focus is lost, but there are still some defects