The AJAX function is failing to return false

I found this code snippet in my index.html file:

<form>
<input onkeyup="firstnamecheck(this.value)" type="text" name="firstname" id="Start" class="Inputs" />
<button type="submit" name="Murad"  id="tester" title="Register">Register</button>
</form>

And here's what I have in reg.js:

function firstnamecheck(str) {
    if (str.length == 0) { 
        document.getElementById("firster").innerHTML = "";
        return false;
    } else if (3 > str.length > 0) {
        document.getElementById("firster").innerHTML = "Firstname should be more than 3 characters";
        return false; 
    } else if (str.length > 30) {
        document.getElementById("firster").innerHTML = "Firstname should be less than 30 characters";
        return false; 
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("firster").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("POST", "era.php?f=" + str, true);
        xmlhttp.send();
    }
}

Despite the errors, the form can still be submitted even when a "return false" is triggered.

Answer №1

Using compound range comparisons such as

if(3>str.length>0)

is not supported in JavaScript, or most (though not all) other languages that stem from B (C, C++, C#, D, Java, JavaScript, etc.).

Instead, you need to specify the two comparisons separately:

if ​​(3 > str.length && str.length > 0)

Answer №2

Building on the insights shared by @TJCrowder, it's crucial to emphasize another key aspect:

It's important to note that your return false; statement is targeting the onkeyup event of the input element, rather than the submit event of the form!

Essentially, there isn't any mechanism in place to prevent the form from being submitted.

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

"Unlock the Power of VueJS 2 with Dynamic Templates

Just starting out as a VueJS student! I created a "MainTemplate.vue", which includes a menu, footer, header... Then I decided to create another .vue file named "ComponentB.vue". Here is the content of my ComponentB.vue file: <template> <h ...

Retro asp with a touch of modern ajax

I am facing an issue with retrieving data from AJAX to ASP. I have a form that includes a select input field, and when I choose one option from the select options, I want to update the value of my form's action tag. $(document).ready(function() { ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Making a dropdown menu spin using Jquery and Javascript

I am in need of a unique solution for a dropdown menu that appears rotated 90 degrees anticlockwise. The goal is to have the dropdown select "button" text displayed vertically, with the options sliding out in a similarly rotated, sideways manner featuring ...

Stopping repeated content with endless scrolling ajax spinner

It seems like my mind is too foggy from the late night hours to find a clear solution, so I thought I'd seek some input from those who have an opinion... The website project I'm currently working on features a lengthy list of user posts. I' ...

Add the element of surprise. The element must be either a Model, an Association, or an object

Struggling with configuring PostgreSQL with Node.js, I followed this tutorial and encountered an error without any specific details: Here is the stacktrace Unhandled rejection Error: Include unexpected. Element has to be either a Model, an Association or ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

Is there an issue with the precedence of jison rules?

I've been stuck for hours trying to solve what seems like a simple problem but I just can't figure it out :/ I'm working on defining a small javascript-like language in jison. The issue I'm facing is that both the Parameter rule and th ...

What is the best way to create a sign-up box that appears on the same page when you click on the sign-up button

I am interested in implementing a 'sign up' box overlay at the center of my index page for new users who do not have an account. I would like them to be able to easily sign up by clicking on the 'sign up' button. Once they complete the ...

Can someone guide me on implementing Node.js clusters in my basic Express application?

— I have successfully developed a basic application that retrieves data (50 items) from a Redis DB and displays it on localhost. After running an ApacheBench test with parameters c = 100, n = 50000, I am achieving around 150 requests/sec on my aging dual ...

Set the class of the list item to "active" class

My approach to styling involves using a UL and li class to contain form selection options. I plan on hiding the radio button and using its value upon form submission. I have managed to enable checking the radio box when the <li> is clicked, but for s ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...

AngularJS modules are not loading dependencies such as constants or controllers

While searching for the reason why a properly defined factory is not loading, I came across this question. This led me to contemplate on the concept of services being "defined in an angular module". Consider this example: angular.module('d3', ...

In a Next.js application directory, how can you retrieve the router.asPath value within a function that utilizes the Next.js navigation feature?

import { useRoute } from "next/navigation" const route = useRoute() const updateData = () => { route.replace(route.asPath); } I attempted using next/router but it was unsuccessful ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

Is it feasible for the web server (IIS) to discern between an AJAX request and a standard one?

Is it possible for a web server, such as IIS, to distinguish between an AJAX request and a regular request? ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Customize the CSS for a Material UI popover styling

I am currently working with a Material UI popover and attempting to apply CSS styles to it. This is the code for my popover component: import React, { memo, useCallback } from 'react'; import PropTypes from 'prop-types'; import { ...

Utilizing AngularJS scope within a modal viewport

I am encountering an issue with my simple controller while fetching and displaying messages using $http.get in HTML using ng-repeat. The problem arises when trying to access the messages from a modal window, as it always prints the first message only. ind ...