when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented:

When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing to the next page (if not empty, advance only if the values are between 0 - 100 numerically).

Currently, this is the code snippet that I am using along with other working code:

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)"; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()";  />
    </div>
</form>

<script>
    function handleChange(input) {
        if (input.value < 0) alert("Value should be between 0 - 100");
        if (input.value > 100) alert("Value should be between 0 - 100");
    }
</script>

The above code works fine where if someone types something in the field and it does not fall between 0 - 100, it will show an alert and prevent page advancement.

However, if the user leaves the field blank, they can still click the submit button and proceed to the next step without any hindrance. To tackle this issue, I tried implementing the following solution (among many others):

<script type = "text/javascript">
    function checkField(){
        var x = document.getElementById("AgencyField").value;
        if (x === ""){
            alert("Value should be between 0 - 100");
            return false;
        } else {
            return true;
        }
    }
</script>

Unfortunately, the above code fails as users can still proceed by clicking the submit button without entering anything in the field.

Your input on resolving this problem would be greatly appreciated!

------------EDIT--------------

After incorporating suggestions from everyone, I made some modifications to my code which has brought it really close to the desired outcome. BUT HERE'S THE ISSUE I AM FACING:

When I input a number greater than 100, the alert message pops up but does NOT ALLOW ADVANCEMENT.

On the other hand, when I leave the field blank, the alert pops up but ALLOWS PROCEEDING.

What could be causing this discrepancy?

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value=""   autocomplete="off" class="forceNumeric" onchange="handleChange(this)"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="handleChange()">
    </div>
</form>

<script>
  function handleChange(input){
  var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") alert("Value should be between 0 - 100");
    }
</script>

-------EDIT #2--------

Below is the full version of my updated code. I am now exclusively using "form onsubmit" and the "onclick" functions as the onchange method was unable to prevent key or button clicks when the form was left empty (i.e., untouched).

The alert displays correctly either on submission or button click, however, the page always advances after closing the alert.

<?php
    $compTime = 8;
    if ($text === '') { $text = 'How likely was it that you caused the tone to occur?|Type your response on a scale from 0-100.'; }
    $texts = explode('|', $text);
    $mainText = array_shift($texts);
?>
<!DOCTYPE html>
<html>
<form onsubmit="return handleChange();">
    <div class="textcenter">
        <h3><?php echo $mainText; ?></h3>
        <?php
            foreach ($texts as $t) {
                echo '<p>' . $t . '</p>';
            }
        ?>
    </div>

    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return handleChange()"/>
    </div>
</form>

<style type="text/css">
img {
    display: block;
    position: relative;
    bottom: -40px;
    left: -21px;
    max-width:520px;
    max-height:520px;
    width: auto;
    height: auto;
}
</style>

<body>
<img src="/tapa/Experiment/images/scale.jpg"</img>
</body>
</html>


<script type="text/javascript">
function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x === "" || x < 0 || x > 100) {
        alert("Value should be between 0 - 100");
        return false;
    }
   return true;
}
</script>

*****EDIT*****

A new script resolved the issue. I appreciate all the contributions and while the suggested solutions were valid, they didn't fit my specific scenario, for reasons I might not entirely comprehend but that's alright.

Answer №1

Make sure to use the triple equals sign (===) instead of the single equals sign (=). Currently, you are assigning an empty string to variable x in a conditional statement rather than checking if a value exists.

if (var x = ""){

The correct syntax should be:

if (x === ""){

Answer №2

Revised inquiry:

If a number greater than 100 is entered, an alert message displays and prevents the form submission.

Entering a number above 100 and clicking submit will trigger the onchange event without submitting the form.

If the field is left blank, it allows form submission after displaying an alert message.

The form advances because it's not instructed to stop. To prevent this, you should return false within the onclick event (see solution below).

Solution:

Add return to the #FormSubmitButton element's onclick attribute:

<input class="button" id="FormSubmitButton" type="submit"
                                            value="Submit" onclick="return handleChange()">
                                                                    ^^^^^^-- include this

Add return statements to the JavaScript function:

function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") {
        alert("Value should be between 0 - 100");
        return false;
    }
    return true;
}

View the updated demo fiddle here.


Initial query

Several issues were identified:

var x = document.getElementById("AgencyField");

In this line of code, x only receives a reference to the #AgencyField element. To retrieve its value, use:

var x = document.getElementById("AgencyField").value;

Furthermore, there is an assignment rather than a comparison in your if statement:

if (var x = ""){

This should be corrected to: if (x === ""){.

Your function checkField() { lacks a closing }.

It's crucial to note:

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()"; />

You need to add a return there (and remove the ;):

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()"/>

For all updates, refer to the working fiddle here. Additional modifications are detailed below (in comments).

Modified JavaScript:

function handleChange(input) {
    if (input.value.length < 0) { // added .length
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    if (input.value.length > 100-1) { // added .length AND subtracted 1
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    return true; // added this
}

function checkField() {
    var x = document.getElementById("AgencyField").value; // added .value
    if (x === "") { // if (var x = "") -> if (x === "")
        alert("Value should be between 0 - 100");
        return false;
    } else {
        return true;
    }
} // added this }

Adjusted HTML:

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onkeypress="return handleChange(this)" ; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()" />
    </div>
</form>
<!-- Adjustments to HTML elements:
#FormSubmitButton
- removed trailing ;
- added return to onclick
#AgencyField
- changed onchange to onkeypress
- included return
-->

Answer №3

Give this a shot:

<script>
    function verifyInput(input) {
        if (input.value < 0 || input.value > 100 || isNaN(input.value)) {
           alert("Please enter a value between 0 and 100");
        }
    }
</script>

Reasoning behind it:

isNan() is a JavaScript method that identifies whether the given parameter is a number. If the input falls out of the range of 0 to 100 or is not a valid number, an alert message will be displayed.

Answer №4

Utilize the onsubmit handler for form validation:

var checkValidity = function(form) {
  var agencyValue = +(form.AgencyField.value) || '';
  if (!agencyValue) {
    alert('Agency field must contain a numeric value!');
    return false;
  } else if (0 > agencyValue || 100 < agencyValue) {
    alert('Agency rating must be between 0 and 100');
    return false;
  } else {
    return true;
  }
};
<form name="agencyForm" onsubmit="return checkValidity(this);">
  <div class="textcenter">
    <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" />
    <input class="button" type="submit" value="Submit" />
  </div>
</form>

Answer №5

Here's how I tackled this challenge.


            <form name="agencytrial" onsubmit="return checkField()">
            <div class="textcenter">
                <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)">
                <input class="button" id="FormSubmitButton" type="submit" value="Submit">
            </div>
            </form>

            <script>
            function handleChange(input) {
              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) alert("Value should be between 0 - 100");
            }
            function checkField(){
              var input = document.getElementById("AgencyField");

              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) {
                alert("Value should be between 0 - 100")
                return false
              }
              return true
            }
            </script>
  1. In my approach, I utilized the onsubmit attribute rather than onclick.
  2. For inaction upon submission, the onsubmit must return false.
  3. Utilizing parseInt simplifies validation procedures.

I hope you have a pleasant day ahead!

Answer №6

My method for validation was as follows:

<form action = "dashboard.php" onsubmit= "return validateForm()">
  <button type="submit" class="button"  id = "submit" name="submit" >Upload to live listing</button>
</form>
    <script type="text/javascript">

       function validateForm(){

        const input = document.getElementById('input1');

        if(input.value === ""){
          alert ("Please enter a value"); // This will prevent the Form from submitting
          return false;                              
        }else{
          return true; // this will submit the form and handle the control to php.
        }
     }

</script>

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

Passing values from Vue3 child component to parent component

Hey there, I'm currently diving into the world of Vue and I'm working on a table that dynamically displays abbreviations. I've been trying to send a searchTerm from my child component to the parent component, but I'm struggling with ge ...

Sending information from Node.js to the backend using AJAX involves a seamless communication process

I'm relatively new to working with AJAX, so please excuse any misunderstandings I may have. I am still in the process of learning. My current task is quite simple. I have a backend file named server.js, an index.html file, and a script.js file. It&ap ...

What is causing the duplication of Google Map drawing controls?

I've been trying to integrate the Google Maps JavaScript API into my React project to create a map with polygon drawing capabilities. The map itself is functioning perfectly fine, but I'm encountering an issue where two sets of drawing controls a ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...

Modify the color or background color of a disabled Material UI checkbox

The disabled unchecked checkbox appears too subtle to me, and I would like to enhance it by giving it a grey background and changing the cursor style to not-allowed. I've been trying to implement these styles on the checkbox using the makeStyles, but ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

Ensure that only a single onmouseover event is triggered when hovering over multiple elements

I want to create a simple code snippet like the one below: <span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span> However, I need to ensure that when hovering ove ...

Locate the child element that has a particular class assigned to it

I need help writing a code to search through all children elements in order to find a div with a specific class. Unfortunately, the DIV I am looking for does not have an ID. Below is the sample HTML that I will be working with: <div class="outerBUB ...

Using the AJAX loading method with an ID stored in a JavaScript variable

Hey there! Could someone please explain how I can use the AJAX load method to load a div whose ID is stored in a JavaScript variable? In other words, the div that needs to be loaded has its ID saved as a JavaScript variable. I'm facing an issue where ...

Tips for activating a deactivated input field in ReactJS

I am trying to create a feature where my textfields are automatically disabled, but can be enabled for editing by clicking an 'Edit' button. Clicking the button again should disable the textfields and save any edits made. I have experimented with ...

Journeying through JSON: Presenting the value alongside its hierarchical parent

I'm completely new to JSON Path, so I'm not sure how complicated this could be, or if it's even possible. The JSON structure I have consists of multiple groups, each containing a set of fields. Both the groups and the fields have their own ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

What is the best way to reset the column filter cell in Material-Table?

Within my Material-Table, I am utilizing this unique TextField to craft a specialized filter cell for each column. My goal is to employ the endAdornment as a button that will reset the filter, but I am struggling with removing the current value. filterCom ...

Backbone "recalling" stored data in attributes

Presented here is a basic model: myTestModel = Backbone.Model.extend({ defaults: { title: 'My Title', config: {}, active: 1, } }) While nothing particularly stands out, there is an interesting observation regardi ...

Using regex to confirm prices are accurate

Can anyone assist me with validating input using regEx in Vue? I'm struggling to create one and haven't been able to find the correct pattern online for what I need. The specific validation I am attempting is for a price value that should be a f ...

Error message "SyntaxError: Unexpected token < in JSON at position 0" encountered while using AJAX

When data is sent through an ajax request and processed, a returned array is encoded into json format. $response = array( 'data' => $leaveData, 'message' => 'Event added successfully', ...

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

Comparison between using jQuery to append and execute a <script> tag versus using vanilla JavaScript

As I enhance my application, I've made the decision to embrace Bootstrap 5, which no longer relies on jQuery. Consequently, I am working to eliminate this dependency from my application entirely. One of the changes I'm making is rewriting the Ja ...

Fixing Sticky Navigation Bar on Scroll (JavaScript, HTML, CSS)

I'm working on this site as a fun side project, but I've hit a roadblock. The sticky nav bar I implemented jumps when the user scrolls down far enough. Despite reading through other discussions, I can't seem to figure out the solution. I su ...

Bootstrap tab content getting shifted downwards

Having an issue with the Tab plugin in Bootstrap on a particular page. The tab body is being pushed down 400px below the actual tabs. This behavior is only occurring on this specific page, while most other pages using the same plugin are functioning fine. ...