Can someone guide me on how to verify a user's input by comparing it against a predefined set of strings in JavaScript?

I am new to JavaScript and still learning, so please bear with me.

I have a unique task of creating multiple voucher codes, each with a specific redeemable amount. When a user purchases a voucher and enters the code in a text field, I need JavaScript to validate the code, confirm the amount redeemed, and display it - similar to how Amazon gift cards work!

All this needs to be implemented in a simple HTML page that I have set up.

As I am just beginning with JS, I have been struggling to figure this out on my own.

For instance, I have several voucher codes stored as strings:

var voucher1 = 'AC60';
var voucher2= 'DC60';
var voucher3= 'RC60';
var voucher4= 'XC60';
var voucher5= 'YC60';
var voucher6= 'WC60';
var voucher7= 'ZC60';

How can I assign a monetary value to each code, validate a user's input, confirm the redeemed amount, and display it, mimicking the process of redeeming Amazon gift cards?

Answer №1

If you're in search of a solution, consider utilizing an Object or a Map. These structures enable you to associate a monetary value with the voucher code through a key-value pair (where the voucher code serves as the key and the monetary value is the value).

An illustration could be demonstrated this way:

// Here is a straightforward object literal consisting of keys and values
const vouchers = {
  AC60: 100,
  DC60: 20,
  RC60: 35,
  XC60: 45,
  YC60: 80,
  WC60: 10,
  ZC60: 200
};

// This function updates the output <div> with the voucher amount 
// or indicates that an unknown voucher was entered
function getVoucherValue(event) {
  const key = input.value;      // Stores the input value
  const value = vouchers[key];  // Searches for the key in the object

  // If the key is valid, update the output <div> with the monetary value
  // Otherwise if the key is undefined, display an error message in the output <div>
  if (vouchers[key]) {
    output.textContent = vouchers[key];
  } else {
    output.textContent = "Invalid voucher"
  }
}

// Whenever the button is clicked, execute the getVoucherValue() function
button.addEventListener("click", getVoucherValue);
<input id="input">
<button id="button">Get Voucher Value</button>
<div id="output"></div>

Answer №2

It's important to note that relying solely on JavaScript validation is not secure, as the value can easily be manipulated and redeemed at any time. To enhance security, consider creating a more robust structure such as an array with objects:

var myArray = [
     { code: "uniqueVoucher1", value: "10.00" },
     { code: "uniqueVoucher2", value: "20.00" },
 ]

You can then use this array to dynamically generate HTML content like so:

for (var i=0;i<myArray.length;i++){
    document.write("<div>Code: " + myArray[i].code + ", Value: " + myArray[i].value + "</div>")
}

This is just a simple example of how you can implement a more secure voucher system.

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

Is an empty string equivalent to false in a boolean context?

I would appreciate further clarification on this subject. I have read several articles, but none have fully answered my questions. ...

Instructions on transferring a variable from JavaScript to PHP once the form is submitted

I'm looking for a solution to dynamically add rows to a table with textfields every time a user clicks a button: <script language = "javascript"> var x = 0; function addRow(){ var tbody = document.getElementById(tabID).getElementsByTagNa ...

A program that removes rows while also decreasing the overall sum

I have implemented a form that allows users to add labor and its price, while also displaying the assigned labor on the same page underneath. My objective is to have functionality where if a user clicks on delete, it will remove the corresponding table ro ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Executing a function within ng-repeat loop four times in AngularJs

In the code snippet below, a ul is populated with 21 phones using HTML: <li ng-repeat="phone in phones" ng-class="{'digestTest': countDigestOccurences(phone) }"> <p>{{phone.snippet}}</p> </li> The JavaScript method cou ...

The Node express GET route experiences intermittent failures when using wildcard match for every other request

I have configured my router to accept any GET request that does not include the word "API" in it. This is specifically for my single page application to handle bookmarked URLs that are not recognized by the app's routes. However, I am encountering an ...

Utilizing $routeParams to dynamically generate the templateUrl with AngularJS

Our platform offers a 2-level navigation system. We are looking to utilize AngularJS $routeProvider to dynamically load templates into an <ng-view />. Here is the approach I am considering: angular.module('myApp', []). config(['$route ...

Entry is automatically added to the form as soon as the page is loaded

I am trying to create a form using PHP, but I want the script to only run after the submit button is pressed. Currently, it runs every time the page loads and overloads the box on the same page. Unfortunately, my knowledge of PHP is limited! Any help wou ...

Unable to utilize query parameters with an ExpressJS API on localhost

Within my index.js file app.use('/api/v1/users', userRouter) In the Router file router.get("/:id", getUserDataById); When using Postman: The GET URL I am using is: http://localhost:3000/api/v1/users?id=120622 The error message is: C ...

The synchronization between the First Column Scroll and Table Filter Function is out of alignment

I haven't coded for a while and my knowledge of JavaScript is still in its early stages, so please excuse me if this question seems a bit naive. Essentially, I've created code that filters an HTML table based on the items in the first column. Th ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

What is the best way to ensure that deck.gl and react-map-gl are displaying properly on my screen?

Check out this code sandbox example that demonstrates my attempt to display a map within a specific component. However, I'm facing an issue where the deck.gl and react-map-gl elements are overflowing outside their parent container and extending to the ...

Ways to determine if a textbox is empty and trigger a popup notification with jQuery

I'm having trouble with checking if the textbox is empty in my form. Every time I try to submit, instead of receiving an alert message saying "Firstname is empty," I get a message that says "Please fill out filled." ('#submit').click(func ...

CSS style to choose the row in a bootstrap table with a specific class

This snippet is from a table created using Bootstrap: <div class="table-responsive"> <table class="table table-bordered table-striped"> <tbody> <tr> <td align="cent ...

Problem with displaying images and videos in a lightbox gallery

Currently, I am encountering an issue with the lightbox feature on my website. When trying to play a video, there seems to be a layer (div tag) blocking it, preventing me from playing or stopping the video. This problem occurs when clicking on an image fir ...

Having difficulty performing raycasting on a singular object within a group in three.js to trigger an animation

Having issues with raycasting into a group in my three.js project. The goal is to trigger animations using TweenMax on object click. However, the problem arises when clicking on an object with another object behind it, causing both animations to be trigge ...

Resizing rectangular images with CSS/Bootstrap into perfect squares

Imagine there is a rectangular image with dimensions of 1400px (height) x 700px (width). I am looking to turn it into a square while maintaining its original proportions and having white sides added. I specifically do not want to crop the image - I want it ...

Guide to creating a synchronous wrapper for jQuery ajax methods

I've made the decision to switch from synchronous ajax calls to asynchronous ones due to lack of support in most modern browsers. My code is currently reliant on synchronous (and dynamic) ajax calls to client-side functions that must be completed befo ...

Guide to sorting a JavaScript array using a filter object

Using a dynamically generated filter object from a multi-search UI component, the data needs to be filtered based on the criteria. Once the user initiates a search, the data will be filtered accordingly. Below is an example of the filter object and sample ...