Accessing website login - <div> and validating user entry

I am currently working on developing a basic login webpage, but I am facing issues with the rendering of the page.

Below is the code I am using:

function logIn(username, password){
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    if(username == "a" && password == "a"){
        window.location.href="awesomePage.html";
    }else{
        alert("Incorrect username or password!");
    }
}
#user {
    position: absolute;
    top: 10px;
    left: 5px;
}
#pass {
    position: absolute;
    top: 40px;
    left: 7.5px;
}
#username {
    position: absolute;
    top: 5px;
    left: 40px;
}
#password {
    position: absolute;
    top: 20px;
    left: 40px;
}
#logIn {
    position: absolute;
    top: 75px;
    left: 80px;
}
<form action="javascript:logIn(username, password);" method="post">
  <div id="user"> Username: </div>
  <div id="username"> 
    <input type="text" id="username" placeholder="Enter username here." /> 
  </div>
  <div id="pass"> Password: </div>
  <div id="password"> 
    <input type="password" id="password" placeholder="Enter password here." /> 
  </div>
  <div id="logIn"> 
    <input type="button" value="Log In" onClick="javascript:logIn(username, password);"/> 
  </div>
</form>

Prior to my changes, after entering a for both username and password and clicking log in, I received an alert message stating: Incorrect username or password.

https://i.sstatic.net/h8dz1.png

In an attempt to resolve the issue, I made the following HTML adjustment:

<div id="un"> <input type="text" id="username" placeholder="Enter username here." /> </div>
<div id="pw"> <input type="password" id="password" placeholder="Enter password here." /> </div>

Consequently, I updated the CSS as follows:

#un {
    position: absolute;
    top: 5px;
    left: 40px;
}
#pw {
    position: absolute;
    top: 20px;
    left: 40px;
}

After making these changes, upon entering a for both username and password, I was successfully redirected to awesomePage.html, however, the input fields were positioned incorrectly.

https://i.sstatic.net/nHJMu.png

My query is: How can I rectify this issue?

Additionally, I have a minor inquiry: Should I name my other pages as awesomePage.html or awesome_page.html, or is Awesome Page.html suitable?

Answer №1

To address your issue with minimal changes in the code:
I made a slight tweak to the CSS and modified the HTML IDs, ensuring that everything remains visually consistent and functional.
Certainly, there is room for improvement by reducing reliance on specific positions, as suggested in previous responses.

function logIn(){
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    debugger;
    if(username == "a" && password == "a"){
        window.location.href="awesomePage.html";
    }else{
        alert("Incorrect username or password!");
    }
}
#user {
    position: absolute;
    top: 10px;
    left: 5px;
}
#pass {
    position: absolute;
    top: 40px;
    left: 7.5px;
}
#username-ctr, #username {
    position: absolute;
    top: 5px;
    left: 40px;
}
#password-ctr, #password {
    position: absolute;
    top: 20px;
    left: 40px;
}
#logIn {
    position: absolute;
    top: 75px;
    left: 80px;
}
<form action="javascript:logIn(username, password);" method="post">
  <div id="user"> Username: </div>
  <div id="username-ctr"> 
    <input type="text" id="username" placeholder="Enter username here." /> 
  </div>
  <div id="pass"> Password: </div>
  <div id="password-ctr"> 
    <input type="password" id="password" placeholder="Enter password here." /> 
  </div>
  <div id="logIn"> 
    <input type="button" value="Log In" onClick="logIn()"/> 
  </div>
</form>

Regarding your second question:
The optimal approach varies depending on several factors, but a search for "website page naming convention" will yield numerous SEO recommendations and best practices. In my opinion, consider the following:
- Avoid using spaces in page names
- Replace underscore (_) with hyphen (-), as some search engines may not treat underscore as a separator
- Maintain consistency in page naming conventions across the website for a better user experience.

Answer №2

According to the feedback provided, it appears that the login currently in place is not functional. One issue identified is the repeated use of IDs within the "div" and "input" elements. To resolve this, updating the IDs to #un for username and #pw for password is recommended. Additionally, adjustments in the CSS will be necessary:

   #username, #un {
    position: absolute;
    top: 5px;
    left: 40px;
   }
   #password, #pw {
    position: absolute;
    top: 20px;
    left: 40px;
   }

Answer №3

Modify your JavaScript code as shown below:

<script type="text/javascript">

function signIn(){
  
    var user = document.querySelector("input[id='user']").value;
    var pass = document.querySelector("input[id='pass']").value;
  
    if(user == "user" && pass == "pass"){
        window.location.href="successPage.html";
    }else{
        alert("Invalid username or password!");
    }
}

</script>

Answer №4

I want to emphasize again, please avoid writing production code like this, as it is not a secure login method. Anyone can view your page source and see your username and password.

To correct the layout issue, you need to apply CSS styling to both the child and parent elements since absolute positioning is being used.

#un, #username {
    position: absolute;
    top: 5px;
    left: 40px;
}
#pw, #password {
    position: absolute;
    top: 20px;
    left: 40px;
}

I also want to explain what was wrong with your original code, as it may assist others in understanding the reason for changing the element IDs.

In your JavaScript function, you are expecting parameters for username and password, but you do not utilize them in your code example. This renders passing them in pointless, and they can be removed from the function definition since you are already using document.getElementById to retrieve both the username and password.

When executing your code and logging the output of the username and password values, you will observe that they both return as undefined. This is due to duplicate ID values in your HTML source, causing the script to fetch the values from the parent div elements instead of the input elements.


  <div id="username"> 
    <input type="text" id="username" placeholder="Enter username here." /> 
  </div>

To rectify this issue, ensure your ID values are unique by changing the input ID to "username_input" or the parent ID to "username_container," and adjust your function accordingly.

Another issue is calling your function twice in the form within your HTML code. While this may not cause immediate problems, complications can arise with asynchronous requests when duplicate requests occur.

<form action="javascript:logIn(username, password);" method="post">

(this is not executed as there is no submit button in your form)

and

<input type="button" value="Log In" onClick="javascript:logIn(username, password);"/>

Omit the action and method in your form element, selecting one or the other.

Here is a revised version of the code on CodePen with the necessary adjustments: http://codepen.io/anon/pen/LbxOOP

To address your additional query, when naming HTML pages directly accessed from the browser, opt for snake case (e.g., awesome_page.html) or hyphens (awesome-page.html). Avoid spaces in file names, as certain setups may not recognize case sensitivity when retrieving the file, leading to unpredictable results with similarly named files.

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

Is it advisable to avoid using XHTML elements, tags, and attributes that will not be included in the HTML 5 specification?

Given that I am currently utilizing XHTML 1.0 Strict, does it make sense to avoid using XHTML elements, tags, and attributes that are not included in the HTML5 specification? For example: <acronym> and <big> ...

Android experiencing issues with dynamically loading Border XML

I am having trouble setting a border dynamically for a RelativeLayout. Oddly enough, when I manually add the border in the activity XML file, it displays perfectly. However, when I try to generate the border dynamically, it doesn't appear. border.xml ...

Discover and modify the values of all the keys within nested JSON arrays and objects using JavaScript

I have a nested JSON data structure consisting of arrays and objects. I am looking to convert all the key values from English to Spanish using JavaScript, NodeJS, or AngularJS. { "firstrootkey" : [ //Array of 6 objects { //1st object ...

The onChange method seems to be malfunctioning when used with radio buttons

I'm having an issue with my form's radio button. It is supposed to do something when the selected item changes, but it only works when the page first loads and not when I select a different item. Below is the code snippet: <div key={item} cla ...

Eliminate unnecessary CSS classes from libraries such as bootstrap when working on a React project

Our team is currently in the process of developing a React project that involves webpack and babel. Our goal is to automatically remove any unused CSS classes from CSS frameworks Bootstrap and AdminLTE 2, which are integral parts of our project. For this ...

Adjustable Text Size with HTML5 and CSS3

Looking to enhance the accessibility of a website by implementing text size adjustment buttons ' A A A ' using just HTML5 and CSS3. Avoiding the use of jQuery or Javascript for this task. Inspiration drawn from this link. Appreciate any assistan ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

What is the best method for populating a text area in Pharo with HTML content?

When logging in through Pharo using an HTML form, you can utilize the method of Znclient called formAt:add: followed by a post. I'm interested to know how I can fill a textArea in an HTML form and then make a post request. Is there a specific method f ...

Numerous categories housed within various div containers

I am working with an HTML code that contains 6 different div elements: <div class="hisclass1 hisclass2 myclass hisclass3"> <div class="herclass1 herclass2"> <!-- 2nd div --> </div> </di ...

Learn how to deactivate the pause button with just one click and re-enable it once the popup appears using Angular2 and Typescript

Can anyone assist with solving an issue I am facing with a timer and a pause button? I need the pause button to be disabled once clicked, until a popup appears, then it should become enabled again. My code snippet is provided below: HTML: <button md-i ...

Display a collection of Mongoose objects in a React component

In my development stack, I rely on node js + React. The data I work with comes from mongoose and typically follows this format: { "_id": "61b711721ad6657fd07ed8ae", "url": "/esports/match/natus-vincere-vs-team-liquid- ...

Can you customize the buttons in the operation panel of an antd image preview window?

https://i.sstatic.net/hZLOn.png I am looking to add a button that allows users to download or share the image being previewed. Is there a way to achieve this functionality? I have researched and read through the documentation but have not found a solutio ...

Is there a way to enhance this Java script file reader into a multi-file reader?

I am seeking assistance with JavaScript as it is not my strong suit, but I require it for my website. My goal is to be able to read the files that I select. Below you can find the input form: <form name="filUpload" action="" method="post" enctype="mul ...

How can you effectively demonstrate that an HTML element is currently being loaded using AJAX?

At times, my application faces the issue of numerous elements loading simultaneously. To address this, I aim to display a customary AJAX spinner above the control (or DOM node) while it remains disabled. What would be the most convenient and effective app ...

Guide to creating flexible routes with multiple changing parameters in Vue 3 using Vue Router

What is the best way to implement dynamic routes with multiple dynamic parameters in any order using Vue 3 and Vue Router? These parameters should be able to be passed in any order. In our web application, we have over 500 views which makes it impractic ...

Error: The parameter "callback" must be in the form of a function

Following a tutorial to upload images to Twitter using Node.js with Twit. Here is the code: function upload_random_image(){ console.log('Opening an image...'); var image_path = path.join(__dirname, '/random_cam/' + random_cam()), ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

What could be causing the submit button to reactivate before all form fields have been completed?

I have implemented the code snippet below to validate each field in my contact form using bootstrap-validator and an additional check through Google reCAPTCHA. You can view and test the form here. The submit button is initially disabled with the following ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Tips for determining the zoom factor through mouse scrolling using jQuery

Is there a way to zoom in on a page when the user scrolls using ctrl + ,? If I determine the Zoom factor, can I then zoom in on the current page based on that factor? For example, if the zoom factor is 1.44, can I convert this to 144% and carry out the ...