Verify whether the array contains the value entered by the user

Currently, I am utilizing an input field to gather user inputs and store them in an array.

The main objective is to verify whether the number inputted by the user already exists in the array. If it does, then the input should not be duplicated.

Below is my implementation:

if(e.keyCode === 43){

    var num = document.getElementById("numbers").value;
    var oks = [];

    // Set value of 'num'


    // Check if 'num' is present in the 'oks' array

    if( oks[num]==num ){

        alert("This number already exists."); 

    }
    else{

        oks[num.value]=num.value;

    }

    console.log(oks.value);


}

However, upon running the code above, the console log displays 'undefined'.

Please assist me in identifying the mistake in my approach.

Thank you for your support :)

Answer №1

Your current code contains several errors that need to be addressed:

var oks = [];

The above code snippet creates an empty array every time the user inputs something, resulting in a useless check for the value's existence. To resolve this issue, you should declare the oks variable outside of the eventListener.

oks[num]

This code does not represent the value; rather, it refers to the element within the array with an index equal to the value, which are two distinct concepts.

num.value

The above statement is erroneous as the num variable represents a number, not a DOM element with a value attribute.

To rectify your problem, here is a potential solution:

if( oks.indexOf(num)>-1 ){
    alert("The value already exists.");
}
else{
    oks.push(num);
}

Answer №2

Here's a simple way to determine if a number is within an array:

if(oks.indexOf(num) != -1) 

Alternatively, you can use the object oks and check if a field with a similar value exists, which may be more efficient:

var oks = [];

Since oks is initialized with each request and always empty, consider initializing it at a parent or global scope for better performance:

var oks = {};
// at a parent scope

if(e.keyCode === 43){

    var num = document.getElementById("numbers").value;
    // set num

    // Check if num is in the oks array
    if( oks{num} != undefined ){

        alert("It is already there."); 

    }
    else{

        oks[num]=true;

    }

    console.log(oks.num);

}

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

The middleware is causing disruptions in the configuration of redis and express

I've recently started using Redis and I'm facing an issue with my middleware 'cache' function that seems to be causing problems in my code. Everything works fine without it, the data displays correctly in the browser, and when I check f ...

Traversing JSON data in a recursive manner without definite knowledge of its size or nesting levels

Currently, I'm working on a chrome app that utilizes local storage. The backend returns JSON data which I then save locally and encrypt all the items within the JSON. I have multiple sets of JSON with different encryption functions for each set. I at ...

Update the variables upon a click event following the completion of an AJAX request

Despite my efforts, I am unable to find a solution to the issue I am currently facing. To address this problem, I have created a script using PHP and jQuery that enables users to promote their "listings" on my website. When users visit a specific page, the ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Guide to ensuring every request in an Express.js application contains a cookie

Currently, I am in the process of developing a CRUD application using both React and Node. As part of my development, it is crucial for me to validate whether the cookie is present or not for each request. app.all("*", (req,res) => { // If the cookie ...

Adding a Javascript value to a WebSQL database

Trying to store the total values of various select lists and radio buttons in a websql database. The initial form inserts correctly, but everything breaks when attempting to add the total variable. Using getElementByID("total") to add it to the table does ...

JavaScript does not acknowledge that one variable is greater than or equal to another

My issue lies in the fact that my code recognizes that 100 is less than 2000, but fails to recognize that 200 is less than 1000. Below is my code snippet (I am also using jQuery as a framework): $('.filter-price').submit(function(e) { var ...

What is the recommended approach for embedding scripts within Angular templates?

I am working on an Angular SPA that consists of multiple tabs, each served by templates. Depending on the tab, different scripts (both local and CDN) are required. Therefore, I am looking for a way to load these scripts only when they are needed, which mea ...

Issue with exporting to Excel in AngularJS in Internet Explorer not functioning as expected

Having some trouble exporting data to Excel or PDF in IE, but it works fine in Chrome. Since most users will be using Internet Explorer, can someone please review my code and provide suggestions? Below is the Angular function I am using: scope. ...

Utilizing Slots in Vue: Accessing Component Methods

I recently started working with Vue and am facing an issue with Vue slots. The component structure is as follows: <template> <div class="dropDown__container"> <div v-show="isOpened" class="dropDown__content" style="display:non ...

Utilizing jQuery Mobile - Dividing content across multiple HTML files

In the process of developing a web application utilizing jQuery and jQuery mobile, I am aiming to display various pages. Given that the corresponding html-markup may become lengthy, I am interested in dividing the html into separate files. For instance: & ...

A BMI calculator function that provides results in string format

Currently, I am enrolled in an online course where one of the tasks given is to develop a BMI (body mass index) calculator. The objective is to create a program that can calculate a user's BMI and provide them with their specific BMI category based on ...

Is there a way to monitor real-time updates without relying on setInterval or timeout functions?

Currently in the process of building a social network, I am working on fetching live notifications. The current approach involves sending an AJAX request every few seconds using setInterval. The code snippet for this operation is as follows: setInterval ( ...

Different Ways to Modify the Appearance of Angular's mat-slide-toggle and mat-checkbox

I am facing an issue in my Angular form where I have a select box containing objects derived from database records. The goal is to automatically populate the form with the object values once one is selected. My Angular application includes an array of obj ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

Is there a way for me to insert a hook into the DOM after a promise has finished updating

Currently, I am tasked with maintaining a code snippet that resembles the following structure: {#await details} {#each values as value, i} <td id="{`${config.id}_${i}`}">{value}</td> {/each} {:then details_result} {#each de ...

Dynamic PHP content manipulated with jQuery Add/Remove functionality

I am new to jQuery and currently working on implementing a feature for my PHP page. I want to have an Add/Remove button/icon that, when clicked, will show a new set of fields (specifically Drop Down menus). The example I found only shows how to add a text ...

Algorithm that continuously increases a given date by 3 months until it surpasses or matches the specified creation date

I am currently working with QuickBase, a platform that involves HTML. My goal is to develop a code that can take a [fixed date] (always in the past) and increment it by 3 months until the MM/YYYY exceeds or equals the MM/YYYY of the [creation date]. Once t ...