Identifying strings from an array in the input using JavaScript and then displaying the identified string

Can you help me create a function that will detect if a user types one of the strings from a list and then output which string was typed in the console?

HTML

<input id="inputText"></input>

JS

window.onload = function(){
  var inputText = document.getElementById('inputText');
  var stringsToDetect = ["apple", "banana", "orange", "grape"]

  inputText.onkeypress = function (e) {
    if (stringsToDetect.includes(inputText.value)) {
      console.log("User typed: " + inputText.value)
    }           
  };                   
}

Answer №1

Consider using the String.indexOf() method along with Array.filter() function.

window.onload = function() {
  var strings = ["string1", "string2", "string3", "string4"];
  /* changed `formula` to `input` */
  document.getElementById('input').oninput = function(e) {
    var find = this.value;
    if (0 < find.length) {
      var matches = strings.filter(function(s) {
        return -1 !== s.indexOf(find);
      });
      console.log('find string', find, ', matches found', matches);
    }
  };
};
<input id="input" />

Answer №2

When fetching an element, make sure to use the correct ID. In this case, the ID of the input should be input, not formula. To correct this mistake, you should check for inclusion in the array instead. Update the code like so:

if (strings.includes(input.value)) {

Also, avoid using the keypress event as it won't capture the updated value immediately. Instead, consider using the oninput event.

Edit 1:

You can utilize Array#some to determine if the input value contains any string from the array.

window.onload = function() {
  var input = document.getElementById('input');
  var strings = ["string1", "string2", "string3", "string4"]

  input.oninput = function(e) {
    if (strings.some(str => input.value.includes(str))) {
      console.log("The input contains the following string:" + input.value)
    }
  };
}
<input id="input"></input>

Answer №3

You can utilize it in this way:-    
formula.onkeypress = function (e) {
      if (strings.includes(input.value)) {
      console.log("The input contains the string:" + input.value)
      }           
    };

Answer №4

Upon reviewing your code, it seems there are a few key issues to address:

  1. The id assigned to the input element is incorrect
  2. Utilizing the onkeyup event will allow you to capture the character immediately as it is typed
  3. Ensure you are utilizing the includes() method with array type variables

window.onload = function(){

var input = document.getElementById('formula');

var strings = ["string1", "string2", "string3", "string4"]

input.onkeyup = function (e) {
  if (strings.includes(input.value)) {
  console.log("Input contains a the string:" + input.value)
  }           
};         

}
<input id="formula" />

Answer №5

Interested in creating an autocomplete form? Check out this helpful resource: Autocomplete

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

Building a dynamic attribute management system with vue and vuetify

In the backend business object, there is a custom attributes data structure that allows clients to add key/value pairs for storing in the database. For instance: Map<String, String> customAttributes; Here's an example of how it would look in th ...

Tips for establishing conditional guidelines and mandatory fields within Vue?

Struggling to implement conditional required fields on a form. The approach I've taken is by setting a data field notRequired: false, and then using it in the fields like this: :required="!notRequired". This allows me to make certain fields not requir ...

Creating a Configuration File for POST Requests in NodeJS Express

In my NodeJS application using Express, I currently have a hardcoded method for handling URL POST Request Calls and responding with JSON Files. This means that every time I need to add more POST Request Inputs or specify which JSON File to use, I have to m ...

Dealing with AJAX errors in React components after mounting

Facebook suggests that the optimal method for loading initial data in a React component is to execute an AJAX request within the componentDidMount function: https://facebook.github.io/react/tips/initial-ajax.html It would look something like this: ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

What is the best method for displaying a radio button as selected based on a variable value?

I have a variable that stores the value of a radio button. After checking certain conditions, I want to dynamically select the radio button based on this value. if(cheque_date == system_date) { cheque_value='Current'; } else { cheque_value ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command: vue create hello-world This generated essential files like HelloWorld.vue, app.vue, and main.js. Next, I followed the documentation on Npm vue-axios to install Axios: npm install --save axios vue-axios In ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

Creating a reduced array based on the contents of the original array

How can I generate a new array based on the contents of another array? Here is what my initial array looks like: Array ( [0] => 1 [type] => first_value_i_need [some_id] => 2 [hits] => 88 [some_other_id] =&g ...

Node.js with Socket.io causes multiple events to be triggered

Currently, I am in the process of developing a rochambo game using node.js and socket.io. The game works as follows: A player places a bet, which is then sent to all other players. These players can choose a sign and click on 'challenge'. Howeve ...

embedding a time frame within a collection of references

I reached out to my Professor via email seeking assistance on this matter, but unfortunately, his response was not very helpful. The task involves finding the optimal placement for an interval of size 50 within a larger set, such that it contains the maxi ...

Is there a discrepancy in the value between data and computed properties in Vue components?

Upon reviewing my code, I have noticed that the value shown in the data of the component does not match the desired value. The code snippet is provided below: View.component('xxx-item',{ props:['item'], template:`xxxx`, computed: ...

Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected. To see this problem in ac ...

Transform a PHP array into a JavaScript array with UTF-8 encoding

I am currently facing an issue with a products table that contains foreign characters. My goal is to utilize a PHP array in JavaScript to filter a dropdown box as the user types. Everything seems to be working fine except when encountering foreign characte ...

Can you explain the significance behind the error message "RangeError: Invalid status code: 0"?

Currently, I'm trying to understand the workings of express and have come up with this get method: app.get('/myendpoint', function(req, res) { var js = JSON.parse ({code: 'success', message:'Valid'}); res.status( ...

What are some tips for utilizing the "bottom-row" slot within the "b-table" component in bootstrap-vue?

I am working on a component that utilizes the bootstrap-vue b-table component. My goal is to create a bottom row that displays the sum of each column in the table. However, I encountered an issue where the bottom-row only fills the first column, leaving ...

Fill the rows of the <Table> using HTML code

I am encountering an issue with displaying data in a table on a screen: <table id="TransactionTable" class="table table-responsive table-striped"> <thead> <tr> <th></th> <th>Date</ ...

Tips for effectively reusing the modal component in Vue.js without encountering re-render issues

I'm encountering an issue where the same component content is being rendered despite having different components (Rendering problem). I have a reusable modal component called modal.vue, so every time I create a new component, I call the modal compone ...