Determine if the input is contained within an array using JavaScript

I'm new to JavaScript and need some help with arrays.

My goal is to verify if the user's input value exists in an array named "fruits" that I have declared. If it does, I want to run a specific piece of code. However, if it doesn't exist in the array, I'd like to display an alert message. I attempted to use the

instanceof

method to check for the value, but none of the conditional statements seem to execute properly. Any insights on what might be going wrong?

$("#submit-btn").bind("click", function() {

           var comment = $("#comments");
            var commentValue = $.trim(comment.val());
            var index;
            var fruits = ["Banana", "Orange", "Apple", "Mango"];
            for (index = 0; index < fruits.length; index++) {
                text += fruits[index];

            if (commentValue.length === 0) {
                alert('Comments are required to continue!');
            } 
            else if (fruits.includes(commentValue)) {
                // Execute code
                });
            }
            else {
                alert('Not a valid fruit');
            }

            return false;
            }
        });

Answer №1

Make sure to place your initial if statement before entering the for loop.

When inside, update the else-if condition as follows:

if(commentValue === fruits[index])

Then, relocate the code from within the else block to outside the for loop.

An alternate method involves the following steps:

if (commentValue.length === 0) {
        alert('Kindly provide comments to proceed!');
       return false;
} 

if(fruits.indexOf(commentValue) > -1) {
    execute code
    return false;
}

alert('Sorry, that is not a valid fruit');
return false;

Answer №2

To check for a match, you can use the indexOf() method. If the result of indexOf is greater than -1, it means there is a match.

Here's an example:

else if (input.indexOf(items[index]) > -1){

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

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

Importing the class results in an undefined outcome

In the process of developing my Vue app, I'm focusing on creating some helper classes: File a.js: export default class Base {//...} File b.js: import Base from "./a" export default class Middle extends Base { // ... } File c.js: import Mi ...

Dynamic filtering with Javascript

I am searching for inspiration on how to create a filter in the left sidebar that dynamically updates the page content when clicked, and if there are subcategories, displays them below the selected filter in the sidebar. I've discovered that AJAX is ...

React not functioning properly when packaged with Webpack

I tried implementing React in the simplest way possible, but I am facing some issues. After bundling React and opening the index.html page, it shows up completely blank with no console errors to indicate any mistakes. Below is my webpack.config.js: const ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

Moving from traditional web pages to a mobile application using NextJS has brought about the error "rest.status is

Currently, I am in the process of upgrading from Next 13.2.5 to version 14.1.0 and switching to using app/api/example/route.js instead of pages/api/example.js. After making these changes, I encountered an error stating TypeError: res.status is not a funct ...

What is the process for implementing a Content Security Policy to enable the loading of external JS files from a CDN in ExpressJS?

When working with ExpressJS, the HTML file is loaded in the following manner: app.use(express.static(__dirname + '/src/templates/')); Within the HTML file, here is an example of a meta tag containing Content Security Policy: <meta http-equiv= ...

I am having trouble retrieving dynamic values from a button using ajax. What could be causing this issue

I decided to create a unique dynamic button that utilizes ajax for calling when it's clicked. Each time the button is clicked, it pulls a fresh list of items from a specific website, resulting in its dynamic behavior. foreach($items as $item_link){ ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

The ArrayList's Object was replaced by the latest iteration

Currently working on a code snippet that generates and updates solutions within an ArrayList. public static void main(String args[]) { ArrayList<sequence> solutions = new ArrayList<sequence>(); int a = 10; sequence alfa = new seque ...

When attempting to fetch data with a dynamic URL in next.js, the error message "undefined is returned

While fetching data on my main page everything works as expected. However, when trying to fetch data in another folder using the same code but with a dynamic URL, I encounter an error when attempting to use methods on an array. Interestingly, when I consol ...

Puppeteer patiently waits for the keyboard.type function to complete typing a lengthy text

Currently, I am utilizing puppeteer for extracting information from a particular website. There is only one straightforward issue with the code snippet below: await page.keyboard.type(data) await page.click(buttonSelector) The initial line involves typin ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

What is the right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

The Node application seems to be encountering an issue when attempting to handle

Whenever I click a button on my page in Node using Express, my JavaScript file sends the following request: toggleCartItem = index => { http = new XMLHttpRequest(); http.open("POST", `/cart_item/${index}`, true); http.send(); } Th ...

Steps for filling an HTML table within a dynamically loaded DIV

I have a container in my HTML page where I dynamically load other pages using the jQuery.load() function. One of the pages requires me to populate a table from the database just after/before it loads. How can I trigger a JavaScript function to execute righ ...

Adding specific values from a matrix in Python

I am working with a matrix of size [n x n] that contains values assigned to different groups, along with a vector of size [1 x n] indicating the group to which each element belongs. (The value of n is typically around 1E4, with n=4 in this example) My goa ...

What's the importance of including (req, res, next) in the bodyParser function within Express?

My original use of bodyParser looked like this: app.use(bodyParser.json()); However, I now have a need to conditionally use bodyParser: app.use((req, res, next) => { if (req.originalUrl === '/hooks') { next(); } else { ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...