Show a checkmark or X depending on the condition in Javascript

I have an array of data that I want to compare to the input in a text field. If the input matches an element in the array, I want to display a checkmark, and if it doesn't match, I want to display a crossmark.

However, I'm having an issue where it either displays a checkmark for all numbers entered or a crossmark. Here is my JavaScript code:

**

    > var data={"number":{"1234","7742","3452","6543","0091"}}; 
function validation(){ 
 var numbersearch =document.getElementById("validate").value;  
for(var i=0; i<data.number.length; i++) {
       if( data.number[i] === numberInput) {
       document.querySelector('.checkmark').style.display = "block"; } 
else if(numberInput === '') { 
     document.querySelector('.checkmark').style.display = "none"; }
 else{
     document.querySelector('.crossmark').style.display = "block"; } } }

**
HTML:
<div>
<input id="validate" type="text" maxlength=4 placeholder="0000">
<svg class="checkmark>
<scg class="crossmark>
</div>

Can someone help me figure out what I'm doing wrong here? I've connected the validation() function to the HTML using an angular component. My goal is to display the class .checkmark when there is a match and .crossmark when there is not a match.

Answer №1

When you identify your number, it's time to break out of the loop. Currently, the code is only checking if the last number in the array matches the input.

To improve this, you should exit the loop as soon as you find a match. Here's how:

for (var i = 0; i < data.number.length; i++) {
    if (data.number[i] === numberInput) {
        document.querySelector('.checkmark').style.display = "block"; 
        break; // This stops the loop
    } 
    else if (numberInput === '') { 
        document.querySelector('.checkmark').style.display = "none"; 
        break; // You should exit here too
    }
    else {
        document.querySelector('.crossmark').style.display = "block";
    } 
}

An alternative approach could be to avoid using a for loop altogether and use the 'contains' function to check if the array contains the input. It can be done like this:


if (numberInput === '') {
    document.querySelector('.checkmark').style.display = "none"; 
} 
else if (data.number.contains(numberInput)) {
    document.querySelector('.checkmark').style.display = "none"; 
} 
else {
    document.querySelector('.crossmark').style.display = "block";
}

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

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

Tips for effectively handling requestAnimationFrame

I created a unique function that both scrambles and translates text. The functionality is smooth if you patiently wait for the animation to finish before moving the mouse over to other elements. However, if you try to rush through to the next one, the prev ...

Learn the method to animate changing the background-color of an element using a click function

Can you create an animation for changing the background color when clicking on an element? Most examples I've found use mouseover/hover functions, but none with a click function. The following line changes the background color without any animation: ...

What is the best way to locate a user-provided string within word boundaries using JavaScript regex?

Employing JavaScript, I am currently searching a body of text. Users are given the option to input any string they desire, and then I aim to search for that specific string, ensuring it is considered a "whole word" located between boundaries. All I need i ...

Determine if two arrays share the same keys

Looking to compare two arrays and update them with matching keys while adding 0 for non-matching keys. For example: let obj1 = [ {"type": "Riesenslalom","total": 2862}, {"type": "Slalom", "total" ...

Encountered a cyclic dependency in MongoDB when attempting to create an index

I have a dataset structured as shown in the image below: https://i.sstatic.net/eu2ZH.png I am attempting to write a query using $near. However, when trying to create an index for this query, I encounter an error stating "cyclic dependency detected". Below ...

The form validation feature is not functioning as expected when integrating mui-places-autocomplete with MUI React

I'm currently working on implementing an autocomplete feature using Google Places API in my project with Material UI React, Redux-Form, Revalidate, and MUI-Places-Autocomplete. Although I've successfully integrated the place lookup functionality, ...

Bring in multiple classes from node_modules

During the development of my package, I have organized my repository with the following structure: src - Requests.js - Constants.js package.json The package.json file contains the following information: { "name": "package-name", "version": " ...

The request for http://localhost:3000/insert.js was terminated due to a 404 (Not Found) error

As someone new to web development, I am currently tackling a project where I'm having trouble loading the Javascript file insert.js. The HTML document upload.html resides in the public folder, while the Javascript file is located in the main folder. I ...

What are the steps to fix a "Cannot read property" error?

Below is a code snippet that is causing an error in the console. This function is part of the service in my Angular application. lastEmployeeID() //code block with error { let temp= this._http.get(this._employeesUrl).subscribe((employees:any ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

The persistent state is not being saved correctly by Redux-Persist and is instead returning the initial

I have included redux-persist in my project, but for some reason it is not persisting the state as expected. Instead, I keep receiving the initial state whenever I reload the page. Below is the snippet of my root-reducer: import { combineReducers } from & ...

The CSS property `touchmove pointer-events: none` appears to have a malfunction on Chrome for Android version 4.4 / ChromeView

For my project, I am utilizing CSS pointer-events to allow touchmove events to pass through a transparent div. This method has been effective on most platforms except for Chrome on Android. I am curious if this is a known issue with Chrome and if there are ...

Implementing CSS animations in ReactJS: A guide to activating onClick and onHover events

Is there a way to activate the onClick and onHover CSS animations for the ReactJS button component below? I attempted to use ref = {input => (this.inputElement = input)}, but I only see the animation when clicking the button. <td> ...

"Creating a dynamic Map using the HERE Maps API and adjusting its size: A step-by-step guide

I am currently working on a Website project and I am interested in incorporating an interactive map from HERE Maps that spans the entire screen under my navigation bar. How can I achieve this? After initially using Google Maps, I switched to HERE Maps due ...

Menu is not functioning properly as it is not staying fixed in place

I am trying to create a fixed menu that sticks to the browser window as it scrolls. However, I am encountering an issue where the transition from sticky to fixed is not smooth when I remove position: relative; from navbar__box. window.onscroll = functio ...

What is the best way to transfer a JSX element from a child component to its parent component?

Is it acceptable to send the JSX element from a parent component to a child component through props? From my understanding, using `useState` to store JSX elements is not recommended. Therefore, I can't just pass a callback down to the child and then ...

Guide to setting up jQuery Mobile with bower

For my project, I'm interested in utilizing jquery-mobile through bower. In order to do so, I need to execute npm install and grunt consecutively within the bower_components/jquery-mobile directory to access the minified .js and .css files. This pro ...

The Material UI month picker interface is not displaying correctly

When trying to implement the code snippet below, <MonthPicker/> I am encountering issues with the UI of the month picker both on the website and at times. https://i.stack.imgur.com/EKsYA.png It seems like the month picker is being utilized in a di ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...