Exploring the Search Functionality in JavaScript Arrays: Tips for Validating Empty Input Fields

After creating a JavaScript array and implementing a search input field box to find matching results, I encountered an issue with the form validation code. It appears that the validation script is being ignored or overridden by the rest of the script.

The problem arises when the input box is left empty and submitted, resulting in a wrong match with no value enclosed within single quotes.

To address this issue, I aim to develop a validation script that first checks if the input box is blank. If it is, the user should be notified that input is required. On the other hand, if the input box is not blank, the remainder of the script should function as intended.

Do you have any suggestions on how to fix this?

Below is the code I currently have:

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Test Search Page</title>
</head>
<body>
<form method="get" action="input" onsubmit="return validate();">
<fieldset>
<input id="formInput" name="formInput" type="text" placeholder="Type Code Number Here" required/>
</fieldset>
</form>
<input id="searchBtn" type="submit" value="Submit">
</body>
</html>

SCRIPT

var data = [{
    code: "2222",
    value: "$10.00"   
}, {
    code: "3333",
    value: "$30.00"
}, {
    code: "4444",
    value: "$50.00"
}, {
    code: "5555",
    value: "$100.00"
}, {
    code: "1111",
    value: "$300.00"
}, {
    code: "7777",
    value: "$500.00"
}, {
    code: "8888",
    value: "$1,000.00"
}, {
    code: "9999",
    value: "$3,000.00"
} ];

//Script for validating an empty input box
function validate()
{
var ch = document.getElementById('formInput');
if(ch.value === '')
{
alert('You Must Enter A Code Number First.');
return false;
}
}

//Script for searching array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
    var formInput = document.getElementById("formInput").value,
        foundItem = null;

    for (i = 0; i < data.length; i++) {
        if (data[i].code == formInput) {
            foundItem = data[i];
            break;
       }
    }

    if (foundItem) {
        alert("Jewellery Code # '" + foundItem.code + "' Value: " + foundItem.value);
    } else {
        alert("Code Number: '" + formInput + "' Was Not Found");
    }

    });

Answer №1

Is there a reason for not relocating the validate function within your existing click event?

var data = [{
  code: "2222",
  value: "$10.00"
}, {
  code: "3333",
  value: "$30.00"
}, {
  code: "4444",
  value: "$50.00"
}, {
  code: "5555",
  value: "$100.00"
}, {
  code: "1111",
  value: "$300.00"
}, {
  code: "7777",
  value: "$500.00"
}, {
  code: "8888",
  value: "$1,000.00"
}, {
  code: "9999",
  value: "$3,000.00"
}];

//Script to search array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
  var formInput = document.getElementById("formInput").value,
    foundItem = null; //we'll store the matching value here

  if (formInput === '') {
    alert('You Must Enter A Code Number First.');
    return false;
  }

  for (i = 0; i < data.length; i++) {
    if (data[i].code == formInput) {
      foundItem = data[i];
      break; //we've found a match, no sense to continue
    }
  }

  if (foundItem) {
    alert("Jewellery Code # '" + foundItem.code + "' Value: " + foundItem.value);
  } else {
    alert("Code Number: '" + formInput + "' Was Not Found");
  }

});
<form method="get" action="input">
  <fieldset>
    <input id="formInput" name="formInput" type="text" placeholder="Type Code Number Here" required/>
  </fieldset>
</form>
<input id="searchBtn" type="submit" value="Submit">

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

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

Is it possible to combine the outcomes of a SQL query that produces numerous entities with identical identifiers?

Currently working on my first Node.js API project. Within the '/posts' endpoint, I am receiving data in this format: [ { "POST_ID": 1, "POST_TITLE": "Post N.1", "POST_DESCRIPTION" ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

Issue with Two Dimensional Array displaying values in grid layout

Currently, I am working on some examples involving 2-dimensional arrays. When attempting to display the output in a specific format like below: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 However, the output I'm getting looks like this: 0 1 2 ...

Utilizing React hooks to optimize shopping cart functionality: Are props and prototypes being used effectively?

As I work on creating a sample shopping cart, I stumbled upon an example that displays each product along with its price, an "add to cart" button, and accurately calculates the total once items are added to the cart. QUERIES 1) Should I be concerned abou ...

PHP code for printing out specific elements in an array

I have an array structured like this: Array ( [0] => Array ( [0] => 2013 [1] => 12 [2] => 52 ) [1] => Array ( [0] => 2013 [1] => 12 [2] => 51 ) [ ...

Leveraging ng-switch with ng-repeat in AngularJS to dynamically apply HTML based on conditions

I have a paginated list of video thumbnails that I want to showcase in a Bootstrap fluid grid. To achieve this, I am utilizing a nested ng-repeat loop to iterate through each list for pagination purposes. Within the inner loop, another ng-repeat is used to ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Guide to tallying the total amount of words within a string by utilizing a for loop in Python 3

I am currently working on a for loop to search for a specific word within a string. While I know there is a one-liner solution in Python, I prefer practicing using for loops to identify individual words as opposed to just individual letters (like vowels). ...

Arrange images in a stack format, scaling them based on their percentage

I'm curious about how to overlap images that are sized using a percentage value (in this case, 100%). If the images had a fixed width/height in pixels, I could easily adjust their positions with position:relative to stack them on top of each other. Ho ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? https://i.sstatic.net/jjogP.png <TextField variant="outlined" label="Quantity" onChan ...

What is the best way to turn an entire table into a clickable link that leads to a different HTML page?

I have created a table that I want to turn into a button linking to another page. The table's values need to be changeable based on data from a database, such as changing the parameter to pH and the value to 7. However, the button should redirect to t ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

Using the ternary operator in Array.map causes issues with Babel's react preset

Check out this code snippet that I'm having trouble with: someArray.map( condition ? element => ({ field: element.someField }) : element => ({ field: element.someOtherField }) I’m currently using Webpack 2.3.3 ...

Parent-Child Communication in VueJS 2.0: How to effectively pass data from the parent component

Does anyone know a straightforward solution to this issue? I've been struggling to find one. Within my HTML file, there's a button that looks like this: <button @click="showModal">Show Modal</button> By clicking on the button, it t ...

Can someone guide me on how to create a feature in JavaScript where users can filter prices by inputting minimum and maximum values?

As a beginner in programming, I am looking to create a filtering feature that allows users to filter results by a specific price range. Users should be able to input a minimum and maximum price to receive a list of items within that range. I am currently ...

What could be the reason for receiving " 0" as an input for my success function?

I am struggling to understand why the retInfo variable is always returning "\r\n\r\n0" when I make an AJAX call. function getEightMore ( ) { // show loading icon $('#load-more-row img').css('visibility', &ap ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Ways to verify email registration using API

app.js client.request .get( 'https://url.dev/api/users/${email}', options ) .then( data => { const userInfo = JSON.parse(data.response).data if (data.ok) { var name = us ...

Sequential cascade filtering without a preset default option

Please note: The following code snippet has been adjusted and is now functional. In a MySQL database table, I have the following columns with corresponding values: Category (Fruit, Vegetable) Type (Apple, Orange, Pumpkin, Potato) Subtype (Red Delicious, ...