"Alert box displaying error message is not appearing on the screen

In order to display an error message using a tooltip, I have hidden the tooltip by setting the style of a span with an id of demo to display:none. Then I use JavaScript's getElementById method to retrieve the value of the input field with an id of userverify to check if it is empty or not. If the value is empty, I set the display property to block and change the innerHTML of the demo element.

function validateForm() {
  var x = document.getElementById("userverify").value;
  var y;
  if (x == "" || x == null) {
    y = document.getElementById("demo").styleDisplay = "block";
    document.getElementById("demo").innerHTML = y + "<h1>Empty Username</h1>";

  }
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}
<form action="" method="" name="">
  <br>
  <br>
  <br>
  <label>Username</label>
  <div class="tooltip">
    <input id="userverify" class="" type="text" name="username">
    <span class="tooltiptext" id="demo" style="display:none">Tooltip text</span>
  </div>
  <input onclick="validateForm()" type="submit" name="submit" value="Submit">

</form>

Answer №1

Initially

let element = document.getElementById("demo").style.display = "block";

This initial code is incorrect, you should use style.display instead.

Also, the tooltip in your second snippet has properties visibility:hidden and opacity:0 that need to be changed along with display.

Snippet from Stack Overflow:

function validateForm() {
  var x = document.getElementById("userverify").value;
  var y = document.getElementById("demo");
  if (x == "" || x == null) {
    y.style.display = "block";
    y.style.visibility = "visible";
    y.style.opacity = "1";
    y.innerHTML = "Please enter a username";

  }
}
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -60px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
  visibility: visible;
  opacity: 1;
}
<form action="" method="" name="">
  <br>
  <br>
  <br>
  <label>Username</label>
  <div class="tooltip">
    <input id="userverify" class="" type="text" name="username">
    <span class="tooltiptext" id="demo" style="display:none">Enter your username here</span>
  </div>
  <input onclick="validateForm()" type="button" name="submit" value="Submit">

</form>

Answer №2

Make sure to update your code with the following changes. Instead of placing the validateForm() function on the submit button, it should be tied to the form element's onSubmit event. By adding onsubmit="return validateForm()", the submission will now rely on the return value of the validateFrom() function.

function validateForm(){

        var x = document.getElementById("userverify").value;
        var y = document.getElementById("demo");
        if(x == "" || x == null){
       y.style.display = "block";
       y.innerHTML = "Empty Username";    
       y.style.visibility = "visible";
       y.style.opacity = "1";
       return false;
        }
        else
        {
            y.style.display = "none";
        }
        
        return true;
}
.tooltip {
    position: relative;
    display: inline-block;
    border-bottom: 1px dotted black;
}

.tooltip .tooltiptext {
    visibility: hidden;
    width: 120px;
    background-color: #555;
    color: #fff;
    text-align: center;
    padding: 5px 0;
    border-radius: 6px;

    position: absolute;
    z-index: 1;
    bottom: 125%;
    left: 50%;
    margin-left: -60px;

    opacity: 0;
    transition: opacity 0.3s;
}

.tooltip .tooltiptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
    visibility: visible;
    opacity: 1;
    }
<form action="#" method="" name="" onsubmit="return validateForm()">
  <br>
  <br>
  <br>
   <label>Username</label>  
     <div class="tooltip">
         <input id="userverify" class="" type="text" name="username"> 
          <span class="tooltiptext" id="demo" style="display:none;">Tooltip text</span>
     </div>
        <input type="submit" name="submit" value="Submit">
                        
                        </form>

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

Turn off hover effect for MUI DataGrid

I'm having trouble figuring out how to disable the hover effect on a row in the MUI Datagrid. I've searched through the API documentation but couldn't find a straightforward solution. Any suggestions on how to achieve this? <DataGrid ...

Begin one lesson, end all others

Looking for help with my expandable list menu that I created using jQuery. Here is the code snippet: $("#menu ul li ul").hide(); $("#menu ul li").click(function() { $(this).find("ul").slideToggle(); }); You can view the fully functional menu on jsFi ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

The navigation bar extends beyond the page's width

Currently, I am working on a website that was started by a former colleague. One issue I have noticed is that when the browser window's resolution reaches 768px or lower, the navigation transforms into a drop-down menu that appears wider than the page ...

Cannot Get jQuery .flip() to Work Automatically Every 2 Seconds

There are 3 words that I want to rotate on their x-axis every 2 seconds (repeating). Using jQuery: $(function () { count = 0; wordsArray = ["Innovation", "Creativity", "Success"]; setInterval(function () { count++; $("#words").text(wordsArray[co ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

"An in-depth guide on parsing JSON and showcasing it in an HTML format

As part of my order processing, I am saving the order details into a JSON file named order_details.json. Here is an example of how the data is structured: [{ "uniqueID": "CHECKOUT_IE01", "orderID": "4001820182", "date": "06-02-2019 16:55:32.32 ...

What is the reason behind the change in size and shape of the text when using "overflow: hidden"?

Check out this interactive demo using the provided HTML and CSS: You can view the demo by clicking on this link. /*CSS*/ .header { margin: 0px; padding: 0px; width: 100%; } .headertable { padding: 0px; margin: 0px; width: 100%; border-sp ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Warning: Potential Infinite Loop when using Vue JS Category Filter

I developed a program that filters events based on their program and type. The program is working correctly, however, an error message stating "You may have an infinite update loop in a component render function" keeps popping up. I suspect that the issue ...

Adding the target='_parent' attribute to the infowindow of a Google Fusion Map by utilizing a click event listener

As someone who is relatively new to Google Fusion, I am eager to expand my knowledge and skills. Recently, I created a customized map with an infowindow and embedded it onto my website using the FusionTablesLayer Wizard. I wanted to avoid using the target= ...

What is the reason for encountering an error when attempting to use a let variable in a new block before reassigning it

Check out this document here where I attempt to explain a coding scenario: // declare variables const x = 1; let y = 2; var z = 3; console.log(`Global scope - x, y, z: ${x}, ${y}, ${z}`); if (true) { console.log(`A new block scope - x, y, z: ${x}, $ ...

Utilize the composition API in Vue.js 3 to call a function and pass in a parameter

I'm having trouble calling a function from another component. When I click on a button in my parent component, formTelemarketing(), it should send data to my other component nAsignedCalls() and call the function getCalls(param) in that component. Thi ...

Is it necessary to download all npm packages when starting a new project?

I recently started learning about npm packages and node. I noticed that when installing packages, they create numerous folders in the "node modules" directory. This got me thinking - when starting a new project, do I need to re-install all these packages ...

Adjusting the width of speech balloon in CSS

This question might seem basic to those who are familiar with CSS (unlike me lol). I'm currently working on incorporating speech balloons into my website using this code from jsfiddle. However, I encountered an issue when the text inside the balloon i ...

Angular routing template failing to execute inline JavaScript code

I'm facing an issue with my Angular.js routing implementation. I have successfully displayed the HTML code in templates using angular.js, but now I am encountering a problem with my template structure: <div id="map_canvas" style="width:95%; heigh ...

Download the ultimate HTML package with a built-in chart.js component directly from your nuxt app

I have a task to create a compact Nuxt application that produces a basic HTML file containing informative sections about the services offered to the clients of my organization. The main purpose is to generate an HTML file that can be easily downloaded and ...

The properties of a JSON object are not explicitly defined

When I make an AJAX call, I receive a JSON object and log it using this code: console.log(response); This is the response that gets logged in the console: {"filename":"new.jpg","orientation":"vertical"} However, when I try to access the orientation pro ...

Switching between a secondary menu using ClassieJS or jQuery?

Currently, the code is configured to toggle the same menu for every icon. To see my current progress, you can check out this fiddle: http://jsfiddle.net/2Lyttauv/ My goal is to have a unique menu for each individual icon. I began by creating the followi ...

Unusual behavior exhibited by dynamic code in iframe

When trying to retrieve a dynamic height iframe, I implement the code below. In the <head> area <script language="javascript" type="text/javascript"> function adjustIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight ...