The premature firing of form validation click events is causing disruptions on all input fields. Additionally, I require assistance in effectively storing and comparing user sign-ins for login purposes at a later stage

I am facing issues with validating form inputs when a click event occurs. Whenever a user clicks inside any input field in my form, the validation process begins even before all fields are filled out. I need a solution where I can submit the form and ensure proper validation at the same time. Despite trying numerous approaches, none of them seem to work. I have identified that the click event should be attached to the anchor tag with the submit image, otherwise, all input fields will respond to the click event but fail to validate the username and password upon adding onclick="return checkForm(this); in the opening anchor tag. I also attempted changing the anchor tag to a button or a div, as well as using jQuery for implementation without success. To sum up, I require effective storage of username and password data followed by login validation code... I have explored several alternatives, all leading to failure, too many to enumerate. Help!

Constantly receiving alerts every time a user switches between input fields is incredibly frustrating. Given my limited experience in this area, I apologize for any incorrect coding practices and posting quirks. Corrections and advice from seasoned individuals are warmly welcomed and greatly appreciated.

Here is an excerpt of my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="js/jquery_library.js"></script>
    <script type="text/javascript">

        alert("Please sign up");

        function checkForm(form)
        {
            // Validation logic
        }

    </script>
    
    /* Additional script snippets */
    
</head>
<body>

<input style="visibility:hidden;" type="text" name="passwordHolder" value="This is your saved pasword:"/>
<h1>User Sign In</h1>
<h2>You must complete and submit the form to return to the homepage.</h2>
<form onclick="return checkForm(this);">
    <p>Username: <input type="text" name="username" value="Enter your username." autofocus="autofocus"></p>
    <p>Password: <input type="password" name="pwd1" id="myPassword" ></p>
    <p>Confirm Password: <input type="password" name="pwd2"></p>
    <p><img  src="img/submitButtonExitOverlayNewsletter.png" name="mySubmitButton" value="submit" value="Re-enter your password."/></p>

    <a href="index.html"  style="background-image: url(img/homepage%20button.gif)"> Home Page</a>

</form>
</body>
</html>

Answer №1

To ensure functionality, it is recommended to utilize onsubmit instead of onclick and include <input type="submit" /> within the form for onsubmit to properly execute.

If styling the submit button is desired, reference this guide: how-can-i-make-my-input-type-submit-an-image

To reset the form, employ the following code snippet:

document.getElementById('myform').reset();

    <!DOCTYPE html><!--this is where I got my password info-->
<html lang="en"><!--http://www.the-art-of-web.com/javascript/validate-password/#box1-->
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <meta charset="UTF-8">
    <title></title>
    
    <script type="text/javascript">

        alert("Sign up please");

        function checkForm(form)
        {
            if(form.username.value == "") {
                alert("Error: Username cannot be blank!");
                form.username.focus();
                return false;
            }
            re = /^\w+$/;
            if(!re.test(form.username.value)) {
                alert("Error: Username must contain only letters, numbers and underscores!");
                form.username.focus();
                return false;
            }

            if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) {
                if(form.pwd1.value.length < 6) {
                    alert("Error: Password must contain at least six characters!");
                    form.pwd1.focus();
                    return false;
                }
                if(form.pwd1.value == form.username.value) {
                    alert("Error: Password must be different from Username!");
                    form.pwd1.focus();
                    return false;
                }
                re = /[0-9]/;
                if(!re.test(form.pwd1.value)) {
                    alert("Error: password must contain at least one number (0-9)!");
                    form.pwd1.focus();
                    return false;
                }
                re = /[a-z]/;
                if(!re.test(form.pwd1.value)) {
                    alert("Error: password must contain at least one lowercase letter (a-z)!");
                    form.pwd1.focus();
                    return false;
                }
                re = /[A-Z]/;
                if(!re.test(form.pwd1.value)) {
                    alert("Error: password must contain at least one uppercase letter (A-Z)!");
                    form.pwd1.focus();
                    return false;
                }
            } else {
                alert("Error: Please check that you've entered and confirmed your password!");
                form.pwd1.focus();
                return false;
            }

//Utilize this code to reset the form 
//          document.getElementById('myform').reset();

            alert("You entered a valid password: " + form.pwd1.value);

            return true;
        }
    </script>
    /*clears my inputs*/
    <script>
      //This part is optional as it clears values on click and focusin
       // $(document).ready(function() {
         //   $('input' ).on('click focusin', function() {
           //     this.value = '';
           // });
    

        // });
    </script>
    /*enters my password into a variable for storage and futer login validation */
    /*The same procedure will be applied to my username...*/
    <script>
        $(document).ready(function() {
            $('img[name="mySubmitButton"]').on('click focusin', function() {
                $('input[name="passwordHolder"]').val($('input[name="pwd1"]').val());
            });
   

        });
    </script>
</head>
<body>

<input style="visibility:hidden;" type="text" name="passwordHolder" value="This is your saved pasword:"/>
<h1>user sign in</h1>
<h2>You must complete and submit the form to get back to home page</h2>
<form onsubmit="return checkForm(this);" id="myform">
    <p>Username: <input type="text" name="username" value="enter your user name." autofocus="autofocus"></p>
    <p>Password: <input type="password" name="pwd1"id="myPassword" ></p>
    <p>Confirm Password: <input type="password" name="pwd2"></p>
    <p><img  src="img/submitButtonExitOverlayNewsletter.png" name="mySubmitButton" value="submit" value="Re-enter your password."/></p>

    <a href="index.html"  style="background-image: url(img/homepage%20button.gif)"> home Page</a>
  <input type="submit" name="submit" value="submit" />

</form>
</body>
</html>

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

Combating React SetState Race Conditions with the Power of Promise.all

componentDidMount() { Promise.all([OfferCreationActions.resetOffer()]).then( () => { OfferCreationActions.updateOfferCreation('viewOnly', true); OfferCreationActions.updateOfferCreation('loadingOffer', true); ...

What is the best method for finding and observing the Javascript code being utilized on a webpage?

Is there a way to find and access specific Javascript used on a webpage? Imagine browsing through a webpage's source code and stumbling upon an element like this: <img border="0" alt="" onmouseout="hidetrail();" onmouseover="showtrail('imag ...

Ways to retrieve component information externally from export

As a newcomer to Vue, I've been experimenting with it before diving into our project, but I've encountered a problem. Typically, when we create an instance like "var app = new Vue ... etc.," we can access its data using app.data. But how do we a ...

Discover the magic of Bootstrap 3.0 Popovers and Tooltips

I'm struggling with implementing the popover and tooltip features in Bootstrap. While I have successfully implemented drop downs and modals, the tooltips are not styled or positioned correctly as shown in the Bootstrap examples, and the popover featur ...

When the height of a mobile browser exceeds 100vh, the content may either scroll or get cut off

I'm facing an issue with a layout that should fit perfectly within the viewport without exceeding its height. Everything looks good on desktop browsers like Chrome, Safari, and Firefox, but when I switch to iOS Chrome/Safari (and possibly Android as w ...

Issue with background repetition in CSS

I'm looking to stretch a background image along the left margin of my webpage. Here's the CSS I'm using: body, html{ height:100%; } #content{ background:url(../images/leftBorder.png); background-repeat:repeat-y; height:100% ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

Is it possible to have ng-map open only remote KML files and not local files?

Currently utilizing Ionic with ng-map for displaying KML files on a map. I need to switch between different KMLs, loading them one at a time upon user request. The remote KMLs load successfully, as evidenced by the following code: <div style="height: 1 ...

Aligning jQuery Mobile Buttons in a List Divider

Seeking assistance with aligning buttons within a list divider in a jQuery mobile app. Take a look at this link to a jsFiddle demonstration I created where the button appears next to the text. Is there a way to align the button to the right without causing ...

Jquery UI Dragging Feature Disabled After Element Dropped

Here is the code I have written: <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <meta name="viewport" content="width=device-width, initial-scale=1> <title>jQuery UI Droppable - Default function ...

JSON manipulation using JavaScript

Looking to dynamically choose a JSON key directly from the JSON Object. var text = '{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}'; var obj = JSON.parse(text); var firstName = obj.employees[0].firstNa ...

Hovering over a td tag and adding a border using CSS can cause the entire table to

While experimenting on a coding platform: <table> <tr> <td class="changeme">something</td> <td>something</td> <td>something</td> <td>something</td> < ...

What could be causing the background to disappear when the window width is reduced?

Can someone please explain why, after reducing the width of the window on , there is no wooden background in the upper right corner? Thank you in advance. ...

Validation of input using JQuery

I am currently working on validating a form, with a specific field that needs to be required. Here is the code for the field in question: <p> <label for="lf">Name: </label> <input class="lf" name="name" type="text"/> < ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

Pressing Accordion Force Open Tab will reveal the contents

Within my PHP script, I have a accordion feature with four tabs. I am looking to include a conditional statement that will determine which tab is initially open. At the moment, all tabs start out closed. <https://jsfiddle.net/9cqo3s73/3/> ...

Include a border around the entire tooltip

I'm having trouble adding a border to my tooltip that follows the outer lines of the entire tooltip. Currently, I've only been able to add a border to the upper part of the tooltip, which overlaps with the arrow section and isn't the desired ...

The jQuery has not been activated

I currently have a list of flags displayed in HTML along with some jQuery code to manage user actions. HTML <a href="#" class="chosenflag" data-flag="de"><img class="flag" src="" alt="" /></a> <ul class="choices"> <li&g ...

Retrieving the _id of a new document in MongoDB using Node.js

I am facing a challenge understanding MongoDB after transitioning from using relational databases. Currently, I am attempting to store an image with the following code: exports.save = function ( input, image, callback) { console.log('Image P ...

Is it possible for JavaScript code to access a file input from the terminal?

When I run the command cat input.txt | node prog.js >result.txt in my terminal, I need to use an input file. This is my code: var fs = require('fs'); var str = fs.readFileSync('input.txt', 'utf8'); str.replace(/^\s* ...