Show a specific element stored within an Array

I'm having trouble making this function work. I want the array to display a specific value in the variable, but it's not functioning as expected. This is the function that's causing me problems:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
if(num == 11) {
    var numCheck = document.getElementById("numCheck").value;
    if (numCheck.indexOf(numbers)) {
        document.getElementById("outputNum").innerHTML = "Yes, the number exists in the array";
        } else {
            document.getElementById("outputNum").innerHTML = "No, the number does not exist in the array";
    }
}

Answer №1

If you are looking to search for a value in an array, the usage of indexOf needs to be adjusted.

Additionally, keep in mind that .value will return a string value. In order to accurately check for its existence, it should first be converted to a number, especially since all values in the array are numeric.

Therefore, the code snippet:

sjkk.indexOf(tall)

should be modified to:

tall.indexOf(Number(sjkk)) !== -1 

or

tall.includes(Number(sjkk))

Answer №2

To accomplish the desired outcome, you can use the following code snippet:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
let uniqueNumbers = {};
numbers.forEach((num) => { uniqueNumbers[num] = 1; });

if(targetNum == 11) {
    var inputNum = document.getElementById("inputNum").value;
    document.getElementById("result").innerHTML = uniqueNumbers[inputNum] ? "Yes, the number exists in the array" : "No, the number does not exist in the array";
}

Answer №3

When using the indexOf method, it is important to apply it correctly to an array as shown below:

if (numbers.indexOf(parseInt(inputValue, 10)) > -1) {
        document.getElementById("result").innerHTML = "Yes, the number is in the array";
        } else {
            document.getElementById("result").innerHTML = "No, the number is not in the array";
    }

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

J-Query J-Player does not autoplay

On my music site, I have integrated jPlayer for playing songs. The songs data is dynamic and added as users select from a list of 10 songs on each page. Although jPlayer adds the songs to the playlist, it does not autoplay. I have tried using playItem=0, p ...

Unable to retrieve the size of the dynamically generated array within the ngOnInit() lifecycle hook in Angular

Recently, I encountered an issue where I couldn't retrieve the length of a dynamically generated array in my Angular application's ngOnInit() method. @Component({ selector: 'rise-our-champions', templateUrl: './our-champions.c ...

Switch out one div for another div in an ASP.NET MVC project

I have a PartialView Here is the code snippet: <div id="question1" style="font-size:20px; margin-bottom:10px;"> @Html.DisplayFor(modelItem => Model.Question1) </div> <div id="question2" style="font-size:20px; margin ...

Guide on making a submit and close button within an overlay

Seeking a button to both submit and close an overlay window. The button code is as follows: <a href="javascript:additem('Info to add here', 10.00,1);" role="button"><button class="purchase btn btn-warning">Select</button></ ...

Exploring the intricate design and information dynamics of MRAID 2

I am currently in the process of developing a new MRAID (v2) compliant SDK for Android that will enable rich media ads to be displayed within various android apps. Additionally, I plan to implement a backend platform that allows advertisers to create their ...

"Exploring Typescript return types in relation to the .getElementsByClassName() method

I am struggling to understand why there is a difference in the results when I use getElementsByClassName on two distinct elements: Check out this code snippet: let section:HTMLElement = document.getElementById("mainSection"); // When I run this, it retu ...

Having trouble with TypeScript configuration of typeRoots and types functionality not functioning correctly

My Current Directory Structure Let me show you the layout of my files: root ├──typings/ # currently empty ├──package.json ├──package-lock.json ├──tsconfig.json └──main.ts This is what my tsconfig.json looks like: { ...

An efficient way to utilize Quicksort for sorting an array of string structures in ANSI C

I have a massive struct of strings containing 3 million lines that I need to sort alphabetically. Initially, I attempted to use bubblesort and it worked fine with a small sample of 10 lines. However, when I tried to apply it to the entire file, it took ove ...

Three.js - demonstrating the play of light and shadows across various perspectives

This particular example showcasing multiple views involves a complex implementation of shadows, rather than opting for the simpler method of just setting an object's property castShadow = true. Is it impossible to use the straightforward approach for ...

Issues arise when attempting to smoothly scroll to an anchor point in a webpage

While working on my website, I have encountered a challenge. The issue arises when dealing with multiple div items. Upon scrolling slightly, the entire page focuses on the div with a height of 100vh, which works perfectly fine. However, my attempts to ...

Automatically customizable CSS border thickness

Consider the following example of a div element: <div style="height: 10%; width: 20%; border: 1px solid black"> Div Content </div> The div above has its height and width specified in percentages. I would like the border width to adjust a ...

JQuery Mobile pop-up error: Property 'is' is not defined

I am attempting to utilize jQuery to open a dialog box. I have followed the instructions provided in this link: Here is the code snippet for the dialog: <div data-role="popup" id="popupDialog" data-overlay-theme="a" data-theme="c" style="max-width ...

Steps to incorporate this jQuery script

After receiving a solution to my problem, I'm struggling with how to actually put it into practice. $(function(){ $.get('file1.php', function(data){ $('#dropdown1').html( data ); }); // when dropdown1 is chang ...

What sets $emit and $dispatch apart in Vue.js?

Vue 2.0 has deprecated the use of $dispatch and $broadcast. I have noticed that $dispatch is similar to $emit. What are the key differences between them? Can we safely replace $dispatch with $emit during migration? ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

Creating a list with different values and modifying its elements using one of the variables

I am currently working on a project that involves extracting events from tables in a calendar application. These events are categorized as either "events" or "repeated events". While I have successfully managed to retrieve individual events, handling repea ...

Transforming an RGB array containing only black or white colors into a binary array (1s and 0s) using Python

Being fairly new to Python, I am currently dealing with an image from a particle detector that is completely black and white. To count the number of hits and eventually separate the hits from different particles, I need to group the adjacent white pixels ...

Issue: Node.js TypeError - Unable to read property

I am a novice in the world of nodejs development, and I have taken on the challenge of creating a blog project to hone my skills. My tech stack includes Node.js Express for the backend and vanilla JavaScript for the client-side. However, I encountered an e ...

What is the best way to import information from a CSV or Excel file directly into my program?

I am currently using puppeteer for automating a form submission process. I am looking to extract data directly from a csv file and input it into the form. Can someone guide me on how to achieve this? The CSV file contains the following information: Fir ...

Hash functionality does not cooperate with the back button, requiring the use of JavaScript to trigger a function when the URL changes

Hi everyone, I have a code snippet that is designed to read the value after the hash in the URL and display a specific div based on that value. It works as expected, except for when the hash is changed while already on the site or when navigating back with ...