Attempting to prevent the insertion of duplicate values more than once

Is there a way to prevent duplicate values from being submitted in my simple site? Currently, I have implemented a function that allows users to input a name and a mark. However, if the same values (name & mark) are entered, I want to notify the user and prevent them from submitting the data again.

function add() {
  name.push(nameInput.value);
  mark.push(markInput.value);

  if (name == "" && mark == "") {
    document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
  } else if (name && mark) {
    document.getElementById("result").innerHTML = "Name & Mark has successfully been entered!";
    console.log(name, mark);
  } else if (name == mark) {
    var n = name.includes("Ross", 0);
    //console.log(name, mark);//
  }
}

document.getElementById("Add").addEventListener("click", insert);

Answer №1

For optimal performance, it is recommended to move the lines name.push(nameInput.value); and mark.push(markInput.value); to a block that fulfills certain criteria for insertion. In this case, the values should not be empty and they must be unique.

if (!name  && !mark ) {
    document.getElementById("result").innerHTML = "No name or mark Has Been Entered. Please Try Again!";
  }
else if (names.includes(nameInput.value) && mark.includes(markInput.value)) {
    document.getElementById("result").innerHTML = "Name & Mark are same please enter again!";
  }
  else{
      names.push(nameInput.value);
      marks.push(markInput.value);
      document.getElementById("result").innerHTML ="Name & Mark has successfully been entered!"
  }

An alternative approach would be to use an object to achieve the same functionality. Create an object with the properties 'name' and 'mark'

 let person = {name: name.value,mark: mark.value };

and then push this object into the arr.

To check for duplicate submissions of the same name and mark, utilize arr.find().

let name = document.getElementById("name");
let mark = document.getElementById("mark");
let arr = [];
const add = () => {
  if (!name.value || !mark.value) {
    alert("Please enter the value in both fields");
    return;
  }
  let person = {
    name: name.value,
    mark: mark.value
  };
  if (arr.find(personIn => personIn.name == person.name && personIn.mark == person.mark)) {
    alert("Please dont repeat the values");
    return;
  }
  arr.push(person);
}
document.getElementById("submit").addEventListener('click', add);
Name:<input type="text" id="name" /><br> Mark:
<input type="text" id="mark" /><br>
<button id="submit">Submit</button>

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

Cookie set upon clicking a particular element exclusively

Looking to toggle a class when clicking an element and preserve it post page load using jQuery or JavaScript. Here's what I currently have, successfully adding the class upon click but not retaining it after reload: jQuery("a.action.towishlist").clic ...

Create a specialized angular controller

Is there a way to create a custom controller programmatically while preserving scope inheritance? I am looking to achieve something similar to this: var controller = 'myCtrl'; var html = '<p>{{value}}</p>'; var validScope= ...

Geocomplete Plugin without Google Branding

I've implemented the jQuery Geocomplete Library. This is what I have accomplished so far- $(function() { $("#find_product_location").geocomplete( { map: "#product_location", mapOptions: { mapTypeId : 'roadmap',//roadmap, satellite,hybrid ...

Contrast: Colon vs. Not Equal Sign (Typescript)

Introduction Hello everyone, I am new to Typescript and currently grappling with some fundamental concepts. When defining a parameter for a function, I typically specify the type like this: function example(test: string){...} However, as I delve deeper ...

`Vanilla JavaScript AJAX request without using any external libraries or

Seeking advice on creating an ajax request function that is compatible across various browsers without relying on a javascript framework such as jQuery. Any ideas or suggestions are appreciated! ...

Assign value to an element in an array using the value from another element

Is it possible in Javascript to set the value of one array element based on another without changing both elements? Specifically, how can I only modify arr[1] while leaving other elements unchanged? arr[0] = {i: 0}; arr[1] = arr[0]; arr[1]['summ&apos ...

Setting up a React Package by reinstalling a git repository

While immersing myself in learning React JS, I decided to create a git repository containing React components that could be exported and used or installed as a package in a separate React application. I developed some UI Components in a git repository and ...

"The authentication scheme is unrecognized" - this is the message produced by Node-LinkedIn module

I am currently utilizing the node-linkedin npm package to authenticate and retrieve information about other users, such as their name, job title, company name, profile picture, and shared connections. While I am able to successfully receive and store the a ...

Exploring the magic of the (!!!) operator in JavaScript!

The !! operator proves to be quite helpful when converting non-boolean data types into Boolean values, mainly for "True" conditions. However, when it comes to false conditions, is using !!! necessary? ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

Checking the dimensions and information of a JSON collection - a step-by-step guide

Recently, I've encountered a JSON String that was returned with an array inside in my Java SpringBoot application. {... "downlineLevels": ["01","02","03","04","05","06","07"] } Unfortunately, only the following JUnit tests have passed. 1) .andExpec ...

How can we develop a NodeJS function that returns a query result using a callback method?

I'm currently working on verifying the proper operation of a database using mocha/chai in NodeJS. I am looking for a solution to run a SQL query and then validate its execution. The issue I'm facing is that when I reach the assertion, the result ...

How to retrieve a DOM element using Aurelia framework

When it comes to accessing a DOM element in Aurelia, what are the best practices to follow for different use cases? Currently, I have two scenarios in my Aurelia project: Firstly, within the template, there is a form that I need to access from the view-mo ...

iOS - A clever trick for manually setting focus on an input/textarea

Recently, there have been numerous discussions about the issue in iOS where focusing on an input/textarea element cannot be achieved through manual means. (Check out the threads here and here) It appears that iOS necessitates a genuine tap or click for foc ...

Mock asynchronous calls in a React component using Jest

I am new to using jest/enzyme and I am facing a challenge in mocking a call to an asynchronous function that returns a Promise. This call is within a react component's componentDidMount method. The purpose of the test is to verify that componentDidMo ...

What could be the reason behind Cesium viewer's failure to show a model after I upload it?

My application features a 3D map of a city with an "Add building" button. Upon clicking this button, a model of a building should be inserted into the map. However, all I see is a selection marker at the intended location without the actual building appea ...

Turn off automatic zooming for mobile device input

One common issue observed in mobile browsers is that they tend to zoom in on an input field or select drop-down when focused. After exploring various solutions, the most elegant one I came across involves setting the font-size of the input field to 16px. W ...

Using JavaScript to implement scrolling functionality for an ASP.NET dropdownlist

On my website, I've created a page with multiple users, each having dropdown lists of items. The issue I encountered was that as the page grew in size and required scrolling, the dropdown lists wouldn't stay in place. Even when scrolling back up, ...

Transitioning the <mat-icon> from one <mat-form-field> to another may not always result in the icon being updated consistently

Being new to Angular, I have been working on creating a form for blog posting and I am trying to include selectable category icons next to the title. In my current setup, I have made a form with selectable font awesome icons. However, I am facing an issue ...

Restoring the position of the <Rect/> element after dragging in a React + Konva application

In my attempt to make a Rect component snap back to its original position using ReactKonva, I defined a Toolbar class with certain dimensions and initial positions for the rectangle. However, after dragging the rectangle and attempting to reset its positio ...