Unlocking Secret Data with External JavaScript

Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML page, the error message is properly shown if the name is less than 6 characters.

However, when I move the JavaScript code to an external .js file, the error message does not appear as intended. Despite the code being identical, the functionality differs based on the placement of the script.

Below is the basic HTML structure for the name input section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Registration Form</title>
    <link type="text/css" rel="stylesheet" href="week12.css" />
    <script type="text/javascript" src="validate.js"></script>
</head>
<body>

<div class="form">
  <table>
    <tr>
        <td><input type="text" name="txtName" id="txtName" placeholder="Name" /></td>
        <td><p class="error" id="txtNameError">Name must be at least 6 characters long.</p></td>
        <!--The p class "error" is set to hidden visibility using the CSS page. If they don't meet the requirements, then "txtNameError" becomes visible.-->
    </tr>
    <tr>
        <td><button onclick="validateForm();">Register</button></td>
    </tr>
  </table>
</div>

</body>
</html>

When I include the function within the HTML page itself, it successfully displays the error message. However, moving the function to validate.js results in the error message not appearing at all.

<script>
    function validateForm() {
        var name = document.getElementById('txtName').value;
        var nameLength = name.length;
        if (nameLength < 6) {
            document.getElementById("txtNameError").style.visibility = "visible";
        }
    }
</script>

It's important to note that when the function is in an external file, the script tags are removed from the HTML page. This distinction seems to be impacting the functionality of the validation process.

Answer №1

Eureka! I have finally cracked the code!

By eliminating one of the variables that was being fetched from the HTML page prematurely, the issue has been resolved. I have now resorted to using an external .js file.

Next on the agenda is to reposition or rework that troublesome variable to prevent any future hiccups.

A big thank you to all for the invaluable assistance provided! :)

Answer №2

You made a spelling error in the function within your script.

Furthermore, it is advised to remove the semicolon in the onclick attribute of your HTML. This adjustment seems to have resolved the errors in my test.

 function validateForm() {
        var name = document.getElementById('txtName').value;
        var nameLength = name.length;
        if (nameLength < 6) {
            document.getElementById("txtNameError").style.visibility = "visible";
        }
    }

and

<td><button onclick="validateForm();">Register</button></td>

should be

<td><button onclick="validateForm()">Register</button></td>

Additionally, I have restructured the code using jQuery for easier manipulation of the HTML elements. If you prefer to stick with JavaScript, I can revise it accordingly. Feel free to view the updated version on jsfiddle: http://jsfiddle.net/dhershman/365r5tg5/1/

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

Button elements are not responsive to Bootstrap margin classes

I am facing an issue in my code where adding the class m-0 to a button is not working to reduce the margin around it to 0. However, when I include .close {margin:0;} in my SCSS file, it successfully reduces the margin to 0. Even though I was advised agains ...

Use jQuery to switch the class of the designated DIV in the showcasing slider

Check out this jQuery slider example where I have two Divs - DIV ONE and DIV TWO. Can you help me figure out how to: 1) Automatically change the class of DIV ONE from "test" to "testc" when Slide 1 is displayed by the slider. 2) Automatically update DIV ...

Leveraging Axios for form data submission

Is it possible to serialize data from an HTML form element and then post the data using a Post request with Axios? Below is the event code triggered when a button click occurs to submit the post: function form_submission(e) { var data = document.getEleme ...

Storing input field values in JavaScript using the onchange event handler.Would you like a different revision

I am looking to calculate the area by multiplying width and height entered into input fields, and then display the result. Any guidance would be greatly appreciated. Thank you! Here is my current code. const width = document.querySelector("#width"); con ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...

Is it time to swap out those divs for tables in your email template?

I have set up my template like this and I am questioning whether I should replace every div with a table. Let's start with the first div in the example. Do I really need to create a new table element, followed by tr and td tags just for a banner? I u ...

Searching for a four-digit number within a string using NodeJS Regex, alongside specific keywords

I have a regex pattern that should match strings with a specific year format. The template is 'Year--"high OR low"-level'. Here is the regex I've created: /Year-\d{4}-\b(low|high)\b-level/gi; When I test it using online regex ...

Tips for avoiding duplicate ids in dynamic divs

I have been working on dynamically creating divs, and while my method is functioning properly, I am encountering an issue with id duplication. Due to restrictions in this scenario, I am only allowed to create 4 additional divs. Below you can find the relev ...

How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection. jQuery(document).ready(function($) { if ($('#user_personal').is(':checked')) { $('.user_co ...

A problem arises when utilizing jQuery's $.isArray functionality

Successfully executing an AJAX post, the function test is utilized to process the passed data. $("#formID").submit(function (event) { $('#postError').html('').hide(); $('#postInfo').html('loading results').s ...

Getting an image using a NodeJS server and Angular frontend: A step-by-step guide

I'm having an issue with displaying images from the server on the frontend. The routes seem to be failing. When I register a user, I save their image on the server using Multer, and store the image path in the database. However, when trying to displ ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...

What could be causing the issue of rows being undefined?

Need help creating a user registration feature with Passport(Local-Signup)? Check out the code snippet below: // config/passport.js // requiring necessary modules var LocalStrategy = require('passport-local').Strategy; // loading the user mode ...

Is there a way to dynamically set the width in CSS based on the width of characters used?

The value of rem is based on font height. Therefore, when setting width in rem for layout or media query purposes, it is determined by the height of the characters, not the width. I believe this may not be ideal for creating layouts. ...

Can you elaborate on the contrast between React Server Components (RSC) and Server Side Rendering (SSR)?

I'm curious about the differences between RSC in React 18 and SSR in NextJS. Can anyone explain? ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

Why has my dropdown menu decided to go horizontal, rather than dropping down as it should?

Hi there! I'm new to css and tried following a tutorial with some tweaks. However, when adding a drop down menu using lists, it ended up going sideways instead of downward. Can anyone help me out? I also would like to have a collapsible menu implemen ...

Is there a way to adjust the placement of this AccordionDetails utilizing Material UI's Grid system?

Here is a sketch of what I am aiming for: https://i.sstatic.net/SFHSpm.png This is my implementation using Material UI's Accordion component. https://i.sstatic.net/JyhCym.png Below is the code snippet for the AccordionDetails section, which is whe ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Content is the main driver for CSS Flexbox dynamic aspect-ratio code

When creating a grid layout for a webpage, I opted to use Flexbox. My goal was to incorporate some automatic functionality so that additional grid boxes could be included without the need to manually add classes or styles in the HTML code. One particular f ...