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

Determine the dimensions of a div element in IE after adjusting its height to auto

I am currently working on a JavaScript function that modifies the size of certain content. In order to accomplish this, I need to obtain the height of a specific div element within my content structure. Below is an example of the HTML code I am dealing wit ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...

How to extract and compare elements from an array using Typescript in Angular 6

I have created a new Angular component with the following code: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Compone ...

What is the best way to comprehend this asynchronous exercise with async/await?

Currently, I am working on some exercises related to async/await, and I seem to be stuck on the following problem: The function ​​opA​ should be executed before ​opB​, and ​opB​ should be executed before ​opC​. Arrange the function call ...

How can we align the top edge of a div to the center of a circle within a separate div in a responsive manner?

I want to create 2 stacked divs: the first div contains a circular image, and the second div contains text. I want the second div to always cover half of the circle, with its upper edge positioned at the center point of the circle. This is my code: .cov ...

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

Every time I attempt to use the PUT method, I receive an error message stating

Controller public function edit(Product $product) { return view('products_update', compact('product')); } public function edit(Product $product) { return view('products_update', compact('product')); } p ...

BreezeJS model, Knockout integration, empty relationships

I am facing an issue where, when using breeze manager.saveChanges(), only the navigation properties are not sent to the server. The rest of the data is being transferred properly. I am relatively new to Breezejs and hoping someone experienced can assist me ...

Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one ...

What is the best way to update my React components to switch from a dark theme to a light theme?

Currently, I am attempting to switch between a light and dark theme in React by utilizing a Switch component from material-ui. Strangely, the theme only toggles once from dark to light. If you want to take a look at the full code, you can find it on this C ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Unable to locate React.js refs within object

import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap'; export default class UserPicForm extends React.Component { constructor() { super(); // establish bindings this.handleSubmission = this.handleSubmission ...

Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal: <script> $(document).ready(function () { $(".total").click(function () { $("#pi ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Tips on obtaining the response (in JSON format) in your console when accessing a URL

Can someone help me integrate this code into my project and guide me on how to proceed with it? function validate() { var un = document.loginscreen.uname.value; var pw = document.loginscreen.psw.value; var username = "John_Smith"; var passw ...

Invoking Ajax to communicate with a Symfony controller

Having some trouble calling a method using ajax. The ajax connection is successful and no error messages are appearing. Here's the JS code: $("[id^=changeStatus]").each(function(){ $(this).on("click", function(){ const id = $(th ...

After submitting the form, Axios sends multiple requests simultaneously

Recently, I embarked on a small project that involves using Laravel and Nuxt Js. The main objective of the project is to create a form for adding users to the database. Everything seems to be progressing smoothly, but there's a minor issue that I&apos ...

What is the best way to remove excess content that falls outside the viewBox?

Is there a function or method to trim a path that extends beyond the viewbox rather than simply concealing it? I am currently using svg-edit, which has a specific viewbox or canvas area. Any elements drawn outside of this canvas remain hidden. However, wh ...

Display/Conceal Dropdown Menu for Combobox Using only Javascript

In my asp.net user control, I am generating markup that looks like this: <div id="combobox1"> <div id="combobox1_text"><span>combobox 1</span></div> <div id="combobox1_ddl"> <input type="checkbox" id="combobo ...

Retrieving the response value in AngularJS with $resource

I'm trying to retrieve the response of a request using $resource in AngularJS. Here is an example implementation: angular.module('app').factory('AuthResource', ['$resource', function($resource) { return { isA ...