What is the best method to determine if a text box is filled or empty?

I need to verify whether a text box is populated with a name. If it is empty, an alert message should be shown upon clicking the submit button, and the page should not proceed with submitting the blank value. If there is a value in the text box, then that value should be submitted.

Below is the code I am currently using. When I leave the text box empty and click on the submit button, the alert pops up as expected. However, the form still submits the empty value after dismissing the alert.

<html>
    <head>
        <script type="text/javascript">

            function check()
            {
                if (!frm1.FileName.value)
                {
                    alert ("Please Enter a File Name");
                    return (false);
                }
                return (true);
            }

        </script>
    </head>
    <body>
        <form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
            <input type="text" name="FileName" id="FileName">       
            <input type="submit" value="send" name="btn_move" id="btn_move" onclick="check()">
        </form>
    </body>
</html>

What could be causing this issue in the code?

Answer №1

Make sure to include onclick="return check();"

Answer №2

Here is a simple HTML form validation script:

<html>
    <head>
        <script type="text/javascript">

            function check()
            {
                if (document.getElementById('FileName').value==""
                 || document.getElementById('FileName').value==undefined)
                {
                    alert ("Please Enter a File Name");
                    return false;
                }
                return true;
            }

        </script>
    </head>
    <body>
        <form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
            <input type="text" name="FileName" id="FileName">       
            <input type="submit" value="send" name="btn_move" id="btn_move" onclick="return check();">
        </form>
    </body>
</html>

Answer №3

When you use the check function and return false, it's important to remember that you need to also return the value from the event handler itself.

By returning false from the event handler, you are able to prevent the default action (such as submitting a form). Here's an example of how this can be implemented:

onclick="return check();"

If you're looking to learn more about event handling beyond inline event handlers, I recommend checking out the informative introduction to event handlers at quirksmode.org.


A best practice is to perform these checks right before a form is submitted, rather than when the submit button is pressed. One way to do this is by binding the event handler to the submit event of the form. Here's an example using traditional event handlers:

document.getElementById('frm1').onsubmit = function() {
    if (!this.FileName.value) {
        alert ("Please Enter a File Name");
        return false;
    }
};

The benefit of this approach is that the validation will occur for all form submissions, not just when the submit button is clicked (for instance, if the enter key triggers form submission).

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

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

Unable to get click function to work with multiple div elements

Using four div elements, I have implemented a feature where clicking on the first div causes all other div elements to change opacity. This is working correctly. However, I would like the opacity of the first div to remain unchanged when moving to another ...

Attempting to adjust numerical values to display with precise two decimal places using jQuery

Possible Redundancy: JavaScript: how to format a number with only two decimal places I'm getting confused while using variables and now I can't seem to get the calculation working correctly. Any ideas? $("#discount").change(function(){ ...

Efficient method to access two arrays simultaneously and combine them into an associative array in JavaScript

When using Ajax to return a table, you have the option of separating column names and row values. Here are two ways to do it: let columns = ["col1", "col2", "col3"]; let rows = [ ["row 1 col 1", "row 1 col 2", "row 1 col 3"] , ["row 2 col 1", "r ...

Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive. I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am face ...

Changing characters to asterisks using Javascript

I am currently working on a function that transforms all characters after the first word into asterisks. For example, if I have MYFIRSTWORD MYSECONDWORD, I would like it to show as: MYFIRSTWORD *** Currently, I'm using the code below which replaces ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

How come it is not possible for me to choose all elements containing an attribute value saved in a variable?

Imagine you have the following snippet of HTML code: <div data-id=5>...</div> <img data-id=5 src=...> <input data-id=5 ...> ... Your task is to select and remove all elements with the attribute data-id set to 5. Here is one attemp ...

Can we display various React components based on the screen size?

I am looking to implement various components that will display at different breakpoints. I attempted this using Material-UI import withWidth, { isWidthUp } from '@material-ui/core/withWidth'; function MyComponent(props) { if (isWidthUp('s ...

I'm struggling to get this if statement to function properly in my JavaScript code - can anyone help? :)

I have encountered an issue with two functions that are meant to retrieve the user_id of a user. One function obtains the session user_id, while the other retrieves the id from the URL like this: profile.html?id=123. Below is the code snippet: // Extracti ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...

Converting an MVC form into JSON using Jquery

I am encountering an issue with serializing my MVC form to JSON using JQuery and then deserializing some values, like the input field value, on the backend in C#. I have tried to serialize it in JSON without success. Can someone please assist me with this ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

The useStyles function does not automatically update properties in response to changes in variables

I have encountered an issue where the style of a component is not changing based on a boolean state change until I refresh the page. Here's what I'm doing: Within my parent App component, I have the following code: import React from "react"; imp ...

Implementing dynamic title rendering based on image in vue.js

This is the code I'm working with, aiming to display slider data. My goal is that if image[0] appears on the slider, it should return title [0]. I'm quite curious about what could be missing in my setup.code-image ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

Adding color between lines in Three.js

I have two different sets of vertices. One set contains real vertices, and the other set contains the same vertices but with a y value of zero. I am trying to connect these vertices and fill them in but have not been successful so far. I have attempted to ...

JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item usi ...

Unfortunately, CSS3 PIE is not compatible with border-radius and box-shadow properties

I created a basic HTML/CSS code for testing purposes, but I'm having trouble getting the library to function properly. I've placed the .htc, .php and .js files in the same directory as index.html, but it just won't work. Check out the code ...