Switch to a different form when clicked using JavaScript

Can you assist me with my code issue?

The scenario is as follows: I have two forms - one for registration and one for login.

I want to dynamically replace the login form with the register form when the user clicks on the "Sign up" link. Similarly, if the user already has an account, I'd like to switch out the register form for the login form when they click on the "Log in" link.

Below are the two forms provided:


         <!-- Login form -->
         <div class="log form" id="login">
            <h2>Log in</h2>
            <form class="form_log">
                 <div>
                     <label for="login">Login : </label>
                     <input type="text" name="login" id="login" required>
                 </div>

                 <div>
                     <label for="password">Password : </label>
                     <input type="text" name="password" id="password" required>
                 </div>

                 <div>
                     <input type="submit" value="Connexion">
                 </div>

                 <p>Don't have an account ? <a href="#" onclick="display('#register')">Sign up</a></p>
             </form>
          </div>

          <!-- Register form -->
          <div class="register form" id="register">
             <h2>Sign up</h2>
             <form class="form_register">
                <div>
                   <label for="login">Login : </label>
                   <input type="text" name="login" id="login" required>
                </div>

                <div>
                   <label for="password">Password : </label>
                   <input type="text" name="password" id="password" required>
                </div>

                <div>
                   <input type="submit" value="Connexion">
                </div>

                <p>Already registered ? <a href="#" onclick="display('#login')">Log in</a></p>
              </form>
          </div>

Script :

 $(document).ready(function(){
      function display (open){
         $(open).css("display", "block");
         $(".form").not($(open)).css("display","none");
      }
 });

I believe there might be a missing or incorrect element in my code, but I'm not entirely sure what it is.

Answer №1

Toggle function can switch between displaying two forms

function display() {
   $("#login").toggle();
   $("#register").toggle();

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Login form -->
         <div class="log form" id="login" style="display: none">
            <h2>Log in</h2>
            <form class="form_log">
                 <div>
                     <label for="login">Login : </label>
                     <input type="text" name="login" id="login" required>
                 </div>

                 <div>
                     <label for="password">Password : </label>
                     <input type="text" name="password" id="password" required>
                 </div>

                 <div>
                     <input type="submit" value="Connexion">
                 </div>

                 <p>Don't have an account ? <a href="#" onclick="display('#register')">Sign up</a></p>
             </form>
          </div>

          <!-- Register form -->
          <div class="register form" id="register">
             <h2>Sign upn</h2>
             <form class="form_register">
                <div>
                   <label for="login">Login : </label>
                   <input type="text" name="login" id="login" required>
                </div>

                <div>
                   <label for="password">Password : </label>
                   <input type="text" name="password" id="password" required>
                </div>

                <div>
                   <input type="submit" value="Connexion">
                </div>

                <p>Already registered ? <a href="#" onclick="display('#login')">Log in</a></p>
              </form>
          </div>

Answer №2

Consider trying this approach: The issue with your code is that the function needs to be placed inside a ready() event handler.

function display(divId) {
  $('.form').hide();
  $(divId).show();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Login form -->
         <div class="log form" id="login" style="display: none">
            <h2>Log in</h2>
            <form class="form_log">
                 <div>
                     <label for="login">Login : </label>
                     <input type="text" name="login" id="login" required>
                 </div>

                 <div>
                     <label for="password">Password : </label>
                     <input type="text" name="password" id="password" required>
                 </div>

                 <div>
                     <input type="submit" value="Connexion">
                 </div>

                 <p>Don't have an account ? <a href="#" onclick="display('#register')">Sign up</a></p>
             </form>
          </div>

          <!-- Register form -->
          <div class="register form" id="register">
             <h2>Sign upn</h2>
             <form class="form_register">
                <div>
                   <label for="login">Login : </label>
                   <input type="text" name="login" id="login" required>
                </div>

                <div>
                   <label for="password">Password : </label>
                   <input type="text" name="password" id="password" required>
                </div>

                <div>
                   <input type="submit" value="Connexion">
                </div>

                <p>Already registered ? <a href="#" onclick="display('#login')">Log in</a></p>
              </form>
          </div>

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

The reason for the undefined socket.id in the browser is due to a potential

When using console.log(socket), I am able to see a socket object in Firebug. Within this object, there is a property called id and I can view the value of this id. However, when I try to access it directly with console.log(socket.id), the result is undefin ...

React component failing to render even when event is triggered

For my latest project, I am creating a blog using react, next.js, and json-server. The blog is coming along nicely with dynamically loaded blog posts and UI elements. However, I've hit a roadblock when it comes to loading comments dynamically. The sp ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

Why does my event dispatch only run once upon form submission in Svelte JS?

My code successfully fetches data and puts it in a card when new data is added to the input. However, the issue arises when more than one data entry is made - although the data gets added to the database, it does not reflect in the data list. Can anyone he ...

Is it possible to adjust the timezone settings on my GraphQL timestamp data?

I've come across a lot of helpful information regarding the usage of Date() and timezones, but something seems to be off. In my GraphQL setup (sourcing from Sanity), I have configured it to use formatString in this manner: export default function Minu ...

How can I convert a string into JSON format in Node.js?

Imagine this scenario: a HTTP REST API has just sent me a JSON in the form of a string. How can I transform it back into a structured JSON object? ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...

Concealing the primary div within a Vue child component

Is there a way to conceal the primary div within a Vue application created using Vue-CLI? I attempted adding the display property, but it did not solve the problem. I am attempting to hide it within my Channels component. Here is how my main component lo ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

What is the process for running an HTML file on a server that utilizes Cordova plugins?

I'm a beginner in Cordova and recently I created an HTML file which I added to the xampp/htdocs directory and it worked fine. My goal is to create a generic app, but now I want to incorporate the Camera Plug-in into my app. Unfortunately, I am unable ...

Using ui-grid to show cells as drop-down menus

I have a ui-grid example where one of the columns represents gender ('Gender': male, female...). The json data binding to the grid only contains code types like (1, 2, 3...). However, I want to display the gender name such as 'male' if ...

What is the best way to ensure the checkbox functions correctly in this specific situation?

I am utilizing PHP, Smarty, and jQuery in the development of my website. Currently, I am working on implementing checkboxes within a Smarty template. Below is a snippet of my Smarty code related to checkboxes: <table cellpadding="5" cellspacing="0" bor ...

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly. Using momentJS, I created a date object for the desired time. The console confirms that the co ...

PHP is failing to send a JSON response, but no errors are being logged in the PHP error log or displayed in the

Hey there, I'm feeling a bit frustrated and really not a fan of Javascript at all. Can someone please help me figure out why this isn't working? It's frustrating because everything seems fine when I return a simple string instead of trying t ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

Building XML using PHP with relatively extensive information stored in JavaScript

Similar Question: XML <-> JSON conversion in Javascript I have a substantial amount of data stored in JavaScript that I need to convert into an XML file on the PHP server. The process of transforming the data into a JSON object, sending it to PH ...

Extracting Ajax responses and storing them as variables in JavaScript

Currently, I am developing a small PHP script and using the following code for an ajax query: var CODE = $('.code').val(); var CASE = $('.code').attr('case'); $.ajax({ type:'POST', ...