Adding icons to form fields based on the accuracy of the inputs provided

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assignment 2 - Website Building</title>
    <style>
        body {
            box-sizing: border-box;
            font-family: sans-serif;
        }

        #login-container {
            width: 460px;
            margin: 0 auto;
        }


        form label,
        form input {
            width: 100%;
            box-sizing: border-box;
        }

        form input {
            padding: 8px;
        }

        form label {
            font-weight: bold;
        }

        form div {
            margin: 16px 0px;
        }

        .invalid {
            border: 2px solid red;
        }

        .valid {
            border: 2px solid green;
        }

        .error-message {
            color: red;
            margin-top: 8px;
        }

        .success-message {
            color: green;
            margin-top: 8px;
        }
    </style>
    <script src="https://kit.fontawesome.com/dde5f4aaa2.js" crossorigin="anonymous"></script>

</head>

<body>

    <div id="login-container">

        <form id="login-form">
            <div>
                <label for="username">Username:</label>
                <input id="username" type="text">
                <span id="username-error" class="error-message"></span>
                <i class="fa-solid fa-check icon" style="color: #008d63;"></i>
                <i class="fa-solid fa-exclamation icon" style="color: #ed0202;display:none;"></i>
            </div>

            <div>
                <label for="password">Password:</label>
                <input id="password" type="password">
                <span id="password-error" class="error-message"></span>
                <i class="fa-solid fa-check icon" style="color: #008d63;"></i>
                <i class="fa-solid fa-exclamation icon" style="color: #ed0202;display:none;"></i>
            </div>

            <input type="submit" value="Login">
        </form>

        <div id="error-messages"></div>
    </div>

    <script>
        document.getElementById("login-form").addEventListener("submit", function (event) {
            event.preventDefault(); // Prevent form submission

            // Reset previous validation styles
            document.getElementById("username").classList.remove("invalid");
            document.getElementById("password").classList.remove("invalid");
            document.getElementById("username").classList.remove("valid");
            document.getElementById("password").classList.remove("valid");
            document.getElementById("error-messages").innerHTML = "";
            document.getElementById("username-error").textContent = "";
            document.getElementById("password-error").textContent = "";

            // Get input values
            var username = document.getElementById("username").value.trim();
            var password = document.getElementById("password").value.trim();

            var errors = [];

            // Validate username and password
            document.getElementById("username").classList.toggle("invalid", username === "" || username !== "new_user");
            document.getElementById("username").classList.toggle("valid", username === "new_user");
            if (username === "") {
                document.getElementById("username-error").textContent = "Please, enter username";
                errors.push("Username is required.");
            } else if (username !== "new_user") {
                document.getElementById("username-error").textContent = "Please, enter valid username";
                errors.push("Invalid username.");
            }

            document.getElementById("password").classList.toggle("invalid", password === "" || password !== "123456789");
            document.getElementById("password").classList.toggle("valid", password === "123456789");
            if (password === "") {
                document.getElementById("password-error").textContent = "Please, enter password";
                errors.push("password is required.");
            } else if (password !== "123456789") {
                document.getElementById("password-error").textContent = "Please, enter valid password";
                errors.push("Invalid password.");

                // Display error messages
                if (errors.length > 0) {
                    var errorMessageHTML = "<ul class='error-message'>";
                    errors.forEach(function (error) {
                        errorMessageHTML += "<li>" + error + "</li>";
                    });
                    errorMessageHTML += "</ul>";
                    document.getElementById("error-messages").innerHTML = errorMessageHTML;
                } else {
                    // Successful login
                    document.getElementById("username").classList.add("valid");
                    document.getElementById("password").classList.add("valid");
                    document.getElementById("error-messages").innerHTML = "<p class='success-message'>Successful login!</p>";
                }
            }
        })
    </script>

</body>

</html>

What i need: So basically i need forms to show checkmark and x icons respectively depending if form's input is correct/incorrect. Those icons need to be in form field on the right side, i managed to find out how to get them in structure but i dont know how to put them inside forms and make them hidden while forms are without input.

What i tried: tried using positions from css but couldnt manage to get it right

Answer №1

I have reviewed the script file and successfully resolved all errors. Here is your updated and corrected code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assignment 2 - Website Building</title>
    <style>
        body {
            box-sizing: border-box;
            font-family: sans-serif;
        }

        #login-container {
            width: 460px;
            margin: 0 auto;
        }


        form label,
        form input {
            width: 100%;
            box-sizing: border-box;
        }

        form input {
            padding: 8px;
        }

        form label {
            font-weight: bold;
        }

        form div {
            margin: 16px 0px;
        }

        .invalid {
            border: 2px solid red;
        }

        .valid {
            border: 2px solid green;
        }

        .error-message {
            color: red;
            margin-top: 8px;
        }

        .success-message {
            color: green;
            margin-top: 8px;
        }

        .inputField {
            display: flex;
            position: relative;
        }

        .inputField svg {
            position: absolute;
            right: 5px;
            top: 6px;
        }

        .hide {
            display: none;
        }

    </style>
    <script src="https://kit.fontawesome.com/dde5f4aaa2.js" crossorigin="anonymous"></script>

</head>

<body>

    <div id="login-container">

        <form id="login-form">
            <div>
                <label for="username">Username:</label>
                <div class="inputField">
                    <input id="username" type="text">
                    <svg id="check1" fill="#000000" width="22px" height="22px" viewBox="0 0 24 24" id="check" data-name="Line Color" xmlns="http://www.w3.org/2000/svg" class="icon line-color"><polyline id="primary" points="5 12 10 17 19 8" style="fill: none; stroke: rgb(3, 252, 61); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></polyline></svg>
                    <svg id="close1" fill="#000000" width="20px" height="20px" viewBox="0 0 24 24" id="cross" data-name="Line Color" xmlns="http://www.w3.org/2000/svg" class="icon line-color"><line id="primary" x1="19" y1="19" x2="5" y2="5" style="fill: none; stroke: rgb(252, 3, 19); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line><line id="primary-2" data-name="primary" x1="19" y1="5" x2="5" y2="19" style="fill: none; stroke: rgb(252, 3, 19); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line></svg>
                </div>
                <span id="username-error" class="error-message"></span>
            </div>

            <div>
                <label for="password">Password:</label>
                <div class="inputField">
                    <input id="password" type="password">
                    <svg id="check2" fill="#000000" width="22px" height="22px" viewBox="0 0 24 24" id="check" data-name="Line Color" xmlns="http://www.w3.org/2000/svg" class="icon line-color"><polyline id="primary" points="5 12 10 17 19 8" style="fill: none; stroke: rgb(3, 252, 61); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></polyline></svg>
                    <svg id="close2" fill="#000000" width="20px" height="20px" viewBox="0 0 24 24" id="cross" data-name="Line Color" xmlns="http://www.w3.org/2000/svg" class="icon line-color"><line id="primary" x1="19" y1="19" x2="5" y2="5" style="fill: none; stroke: rgb(252, 3, 19); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line><line id="primary-2" data-name="primary" x1="19" y1="5" x2="5" y2="19" style="fill: none; stroke: rgb(252, 3, 19); stroke-linecap: round; stroke-linejoin: round; stroke-width: 2;"></line></svg>
                </div>
                <span id="password-error" class="error-message"></span>
            </div>

            <input type="submit" value="Login">
        </form>

        <div id="error-messages"></div>
    </div>

    <script>
        document.getElementById("check1").classList.add("hide");
        document.getElementById("check2").classList.add("hide");
        document.getElementById("close1").classList.add("hide");
        document.getElementById("close2").classList.add("hide");

        document.getElementById("login-form").addEventListener("submit", function (event) {
            event.preventDefault(); // Prevent form submission

            // Reset previous validation styles
            document.getElementById("username").classList.remove("invalid");
            document.getElementById("password").classList.remove("invalid");
            document.getElementById("username").classList.remove("valid");
            document.getElementById("password").classList.remove("valid");
            document.getElementById("error-messages").innerHTML = "";
            document.getElementById("username-error").textContent = "";
            document.getElementById("password-error").textContent = "";

            // Get input values
            var username = document.getElementById("username").value.trim();
            var password = document.getElementById("password").value.trim();

            var errors = [];

            // Validate username and password
            document.getElementById("username").classList.toggle("invalid", username === "" || username !== "new_user");
            document.getElementById("username").classList.toggle("valid", username === "new_user");

            if (username === "") {
                document.getElementById("username-error").textContent = "Please, enter username";
                errors.push("Username is required.");
            } else if (username !== "new_user") {
                document.getElementById("username-error").textContent = "Please, enter valid username";
                errors.push("Invalid username.");
            }

            if(username === "new_user") {
                document.getElementById("close1").classList.add("hide");
                document.getElementById("check1").classList.remove("hide");
            } else {
                document.getElementById("check1").classList.add("hide");
                document.getElementById("close1").classList.remove("hide");
            }

            document.getElementById("password").classList.toggle("invalid", password === "" || password !== "123456789");
            document.getElementById("password").classList.toggle("valid", password === "123456789");
            if (password === "") {
                document.getElementById("password-error").textContent = "Please, enter password";
                errors.push("password is required.");
            } else if (password !== "123456789") {
                document.getElementById("password-error").textContent = "Please, enter valid password";
                errors.push("Invalid password.");

            } 

            if(password === "123456789") {
                document.getElementById("close2").classList.add("hide");
                document.getElementById("check2").classList.remove("hide");
            } else {
                document.getElementById("check2").classList.add("hide");
                document.getElementById("close2").classList.remove("hide");
            }

            if (errors.length > 0) {
                // Display error messages
                var errorMessageHTML = "<ul class='error-message'>";
                errors.forEach(function (error) {
                    errorMessageHTML += "<li>" + error + "</li>";
                });
                errorMessageHTML += "</ul>";
                document.getElementById("error-messages").innerHTML = errorMessageHTML;
            } else {
                // Successful login
                document.getElementById("username").classList.add("valid");
                document.getElementById("password").classList.add("valid"); 
                document.getElementById("error-messages").innerHTML = "<p class='success-message'>Successful login!</p>";
            }
        })
    </script>

</body>

I have made changes to CSS, HTML, and Script as per your requirements.

HTML Changes

There were font issues in the HTML, so I utilized SVGs instead of fonts. Inputs fields and SVG icons are now grouped inside a div with the class "inputField". Unique IDs have been assigned to each SVG icon for better identification in the script.

CSS Changes

The "inputField" class has been styled with display: flex and position: relative. The SVG icons now have an absolute position with specific top and right properties. The "hide" class is used to initially hide the SVG icons as requested.

Script Changes

All four SVG icons are hidden by default using the "hide" class. Conditions have been added to check the correctness of usernames and passwords. Additionally, error messages are displayed only when there are errors, and success messages are shown upon successful login.

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

Click a Bootstrap button to navigate to a different section on the current webpage

My button CTA is not redirecting to the second part of the webpage despite using onclick and <a href:"#" methods. The button is supposed to link to either the About section or the accordionFlushExample id, but nothing seems to trigger a response. Any s ...

The IntroJs step is only partially visible on the screen

Currently, I am incorporating introJS into my application and encountering an issue where one of the steps is only partially visible on the screen. Despite trying various position settings such as auto, left, right, etc., this particular item consistentl ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Floating divs failing to clear properly in Internet Explorer

Encountered a persistent bug that only seems to occur in Internet Explorer. I have set up a jsFiddle to showcase the issue. <div class="container" style="width: 802px;"> <div class="block"></div> <div class="block"></div> ...

Having trouble vertically aligning text? Combining AngularJS, Bootstrap, and Flexbox can help!

I have spent a lot of time trying to understand why I am unable to vertically align the text inside these cells. I have tried multiple solutions: align-items: center; vertical-align: middle; justify-content: center; justify-items: center; Unfortunately, ...

Using JavaScript to load content with AJAX on skip links

Is there a way to prevent the error "loadWithAjax is not defined" from occurring while using the script below? addEventListener('click', function (ev) { if (ev.target.classList.contains('bpb')) { ev.preventDefault(); ...

Understanding the extent of variables in Javascript

I'm struggling to comprehend the scope of 'this' in this particular situation. I can easily call each of these functions like: this.startTracking(); from within the time tracker switch object. However, when attempting to execute the code: Dr ...

EmeraldSocks Tweenmax motion design

I need help with Tweenmax animation. I'm attempting to animate an id selector, but nothing is happening. Both the selector and content are unresponsive. Can someone assist me? Here is the code: <!DOCTYPE html> <html> <head> ...

reasons for utilizing `this.initialState = this.state;`

Could someone help me understand why I am using this.initialState in a React JS class component setup? class Registration extends Component { constructor(props) { super(props); this.state = { username: '', email: '&apo ...

Having trouble getting the CSS animation to work properly with the text

Update: The direct link is working fine, unlike the rocketscript version. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> I have been attempting to animate word rotati ...

The Nuxt.js authentication module remains in place and does not redirect users who are already logged

An authenticated user can still access the /login page. If I click on a link to the /login page, I am redirected to a different page successfully. However, if I manually type in /login in the URL, I am still taken to the login page even though I am already ...

Obtain specific text from elements on a website

How can I extract a text-only content from a td tag like 'Zubr Polish Lager 6%'? <td width="35%">Amber Storm Scotch Ale 6% <br/>SIZE/LIFE: 330ml <b>CASE</b> <br/>UOS ...

Error message: The function s.t.match is not defined in the context of react-export-excel

I have integrated Excel Export with custom cell styles from the react-export-excel examples in my frontend application. However, I encountered the following error whenever I attempt to click on the Export button. Uncaught TypeError: s.t.match is not a func ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

"PHP Are You Dealing with Excessive Whitespace

Currently, I am utilizing AJAX to handle the processing of my ChangePassword class, which is an extension of my DataProcessor class. For some reason, every data I receive from the AJAX response seems to have an added whitespace before it, almost like it&ap ...

Verifying the execute boolean status or utilizing try/catch with PDO

Apologies for the subpar title. My project heavily relies on AJAX, with most responses returning either 'error' or 'success' messages in an array. In my Javascript code, I display these messages in a custom notification bar. I'm u ...