Attempting to verify JavaScript input by utilizing OnClick and a custom function. Regardless of the content inputted, the system consistently confirms that the format is accurate

I am currently working on a project that involves an HTML file and an external JavaScript file. In the HTML file, there is user input and a validation button that triggers the courseValidation() function when clicked. However, I am facing an issue with the if statement in the JavaScript code. Even when the input does not match myRegExp, it always displays "Correct Format" on the page instead of "Incorrect Format". I'm still learning and would appreciate any guidance or suggestions to help me troubleshoot this issue.

Here is the structure of the files:

<html lang="en">
<head>
<title>Validation</title>
</head>
<body>
    <script src="course.js"></script>
    <p>Enter Course Information:</p>

    <input id="courseCode" type="text">
    <button onclick="courseValidation()">Validate</button>

        <p id="course"></p>
   </body>
</html>

External JavaScript File:

function courseValidation() {
var courseCode = document.getElementById("course").innerHTML;
var myRegExp = /\D{3}.\d{3}#\d{4}_\D{2}-\d{4}/;

if (courseCode.match(myRegExp)) {
    document.write("Incorrect Format");
} else {
    document.write("Correct Format");
}
}

Answer №1

You are encountering an issue in retrieving the input value correctly. To fetch the value of the input field, use

var courseCode = document.getElementById("courseCode").value;
instead of
var courseCode = document.getElementById("course").innerHTML;
.

Furthermore, your conditional if statement is incorrectly ordered. It should be structured like this:

if (courseCode.match(myRegExp)) {
    document.write("Correct Format");
} else {
    document.write("Incorrect Format");
}

Answer №2

The input ID should be courseCode instead of just course, and you are currently using .innerhtml when it should be .value

var courseCode = document.getElementById('courseCode').value

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

Sending a form without the need to reload the page

While it's known that Ajax is the preferred method to submit a form without refreshing the page, going through each field and constructing the Post string can be time-consuming. Is there an alternative approach that utilizes the browser's built-i ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Jquery Validate doesn't consistently give a positive response

Having a button that triggers the jQuery validation plugin poses an issue where it consistently returns true, except when the fields are left empty. The rules set for validation seem to be disregarded. DEMO http://jsfiddle.net/sw87W/835/ $(document).read ...

What is the best way to ensure that your regular expression returns all capture groups?

Looking to extract specific values from a string that follows the pattern RAM 1000/2000/3000/4000. Using regular expressions, how can I extract RAM 1000, 2000, 3000, and 4000? I've tried using (RAM 1000)(?:(?:\/)(\w+)){1,}, but it only capt ...

Trouble with Fetching JSON Data using AJAX

Having trouble retrieving JSON data from an acronym finder API using a simple GET request. Here is the code I'm using: $.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', { crossDomain:true, dataType: "jsonp ...

Concealing Popover with internal click

I am currently implementing Vue-PopperJS in my project, following the setup provided on the linked page with a few modifications: <template> <Popper ref="popover" trigger="clickToToggle" :options="{ pla ...

WebStorm failing to identify Node.js functions

I recently began my journey in learning node.js and I'm currently utilizing WebStorm 11 as my preferred IDE. However, I've encountered an issue where WebStorm does not seem to recognize the writeHead method: var http = require("http"); http.cre ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

How to properly align TableHeader and TableBody contents in a Material-UI table

I am experiencing an issue with a file that is supposed to display a table of data pulled from a database. Although the table does appear, all the data seems to be displayed under the ISSUE NUMBER column, instead of being aligned with their respective col ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

Encountered difficulties while attempting to set up React.js

Why am I encountering difficulties installing React? I managed to create a node module file, but it is being automatically deleted. I ran the command npx create-react-app my-app. Below is a screenshot. Aborting installation. npm install --no-audit --save ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Incorporating the sx attribute into a personalized component

I am currently incorporating MUI v5 along with Gatsby Image in my project. To maintain consistency in my styling syntax throughout the application, I decided to include the sx prop in the GatsbyImage component. This is how I attempted it: <Box compon ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

Just a quick inquiry regarding adding new line characters in JSON to be used in

After encountering an issue with a JSON file in my JavaScript application where it would not print new lines when viewed on the console, I am at a loss for a solution. The contents of my JSON file are as follows: [ { "id": "71046" ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...

Strange rendering in CSS JQuery Datatable

I am encountering an issue with a DataTable from datatables.net. Each row can be selected by clicking on a checkbox, which triggers a click event. In response to the event, I add or remove a CSS class to change the appearance of the selected rows. $(".cbD ...

Utilize JavaScript to trigger a function depending on the selected options from dropdown menus

I've been working on a fun little project for a web page where users can select two items from a drop-down menu and then click a button to play a sound corresponding to their selections. However, I'm facing some challenges with getting my JavaScr ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...