The value you enter contains the following

I try to hide the text if the input value contains any letters of the following (and only matching letters). This is currently caused by any letter, not just the words "england," and I don’t understand why. Any help is greatly appreciated.

var input = document.getElementById("input1")

$("#input1").keypress(function(event) {
  if (event.which == 13) {
    event.preventDefault();
    $("input").submit();
  }
});

input.addEventListener("keyup", function() {
  if ($("input[value*='england']")) {
    $('#etext').hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text" value="" placeholder="Search.. ." />
<p id="etext">England</p>
Run codeHide result
+4
source share
1 answer

This is the wrong check:

if ($("input[value*='england']")) {

You need to change this as follows:

if ($("input").val().toLowerCase().indexOf("england") === 0) {

Above code:

  • Returns the current value <input>.
  • Converts to lowercase.
  • Checks if the index is englandsource.

And also you do not need to mix pure JavaScript and jQuery. Use the same code and enclose everything inside the event document ready.

$(function() {
  var input = document.getElementById("input1");

  $("#input1").keypress(function(event) {
    if (event.which == 13) {
      event.preventDefault();
      $("input").submit();
    }
  });

  $("#input1").on("keyup", function () {
    if ($(this).val().toLowerCase().indexOf("england") === 0) {
      $('#etext').hide();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1" type="text" value="" placeholder="Search.. ." />
<p id="etext">England</p>
Run codeHide result

. , value , value . if ($(selector)) , $()

, , ;. .

+7

Source: https://habr.com/ru/post/1664110/


All Articles