Search code examples
javascriptinputbox

Input box that triggers function on keyword


How do I code an input box, that triggers a certain function, if I enter "x" into this input box? (I am using HTML and JavaScript)

This is the code I tried:

<form>
<input type="text" placeholder="Type " id="inputId_1"></input>

<button type="button" onclick="getInputValue();">Get Value</button>
</form>

<script>
function getInputValue() {
      let an = document.getElementById(inputId_1).value;
    
     if (an == "k") {
    document.getElementById("iftest") = "zero was entered";
}
</script>
<p id ="iftest">Hello</p>

Solution

  • A generic approach that allows a custom match value introduces kind of a reusable component which is identified by its specific custom data- attribute and initialized via querySelectorAll and/or querySelector.

    The initializing process is very basic and takes care of a component's event handling by adding a generically implemented handler function via addEventListener to each identified input-element.

    The low level generic handler gets triggered by any input value change and derives all necessary data from the passed event object.

    Both values the input element's value and the match value of an input element's dataset will be toLowerCased before trying to figure out whether they match partially or not via value.includes(match).

    In both cases one is going to use the related HTML output element, in the former case one renders an error specific message in the latter one would clear the output.

    function handleTextInputMatch(evt) {
      const elmInput = evt.currentTarget;
      const elmOutput = elmInput.parentNode.querySelector('output');
    
      const value = elmInput.value.toLowerCase();
      const match = elmInput.dataset.match.toLowerCase();
    
      if (value.includes(match)) {
    
        elmOutput.textContent = elmInput.dataset.matchOutput;
      } else {
        elmOutput.textContent = '';
      }
    }
    
    function initialize() {
      document
        .querySelectorAll('[data-text-input-match] [data-match]')
        .forEach(elmInput =>
          elmInput.addEventListener('input', handleTextInputMatch)
        );
    }
    
    initialize();
    output { color: #c00; }
    <form>
      <fieldset data-text-input-match>
        <legend>
          no "XXX" in any case
        </legend>
        <input
          type="text"
          data-match="xxx"
          data-match-output="partially invalid input value"
        />
        <output></output>
      </fieldset>
    
      <fieldset data-text-input-match>
        <legend>
          no "Foo" in any case
        </legend>
        <input
          type="text"
          data-match="FOO"
          data-match-output="invalid character sequence"
        />
        <output></output>
      </fieldset>
    </form>