Ensuring maximum length validation on input

I am having an issue with the function "checkNumbers()". I am attempting to validate if my input does not exceed 10 numbers; while "isAllowedSymbol()" is functioning correctly, the other one is not. What could be causing this problem?

 function isAllowedSymbol(input)
        { 
            var value = input.value; 
            var rep = /[a-zA-Z]/;
            var rep2 = /[а-яА-Я]/;

        if (rep.test(value))
        { 
        value = value.replace(rep, ''); 
        input.value = value; 
                if (rep2.test(value))
                { 
                value = value.replace(rep2, ''); 
                input.value = value; 
                }
        } 
    }
    var element = document.querySelector("input[name=answer]");


    function checkNumbers(element) {
      if (element != null && element.value.length > 10) {
        element = element.replace(element, '');
      }
    }

<input type="text" maxlength="10" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this);" placeholder="Enter data" > <br>

Answer №1

What is your desired action? If you want the input box to clear when the input exceeds 10 characters, first modify the maxlength attribute of the input box.

<input type="text" maxlength="15" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this);" placeholder="Enter data">

Answer №2

By setting the maxlength = 10 for the input, you have restricted the ability to add new characters. Therefore, the condition element.value.length > 10 will never be met.

Here is an alternative solution:

function isAllowedSymbol(input)
        { 
            var value = input.value; 
            var rep = /[a-zA-Z]/;
            var rep2 = /[а-яА-Я]/;

        if (rep.test(value))
        { 
        value = value.replace(rep, ''); 
        input.value = value; 
                if (rep2.test(value))
                { 
                value = value.replace(rep2, ''); 
                input.value = value; 
                }
        } 
    }
    var element = document.querySelector("input[name=answer]");


    function checkNumbers(element) {
      if (element != null && element.value.length > 10) {
        element.value = ''
      }
    }
<input type="text" maxlength="15" name="answer" onkeyup="isAllowedSymbol(this);checkNumbers(this);" placeholder="Enter data" > <br>

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

What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays - const source = [1, 1, 1, 3, 4]; const target = [1, 2, 4, 5, 6]; Initializing Arrays - const matches1 = []; const matches2 = []; const unmatches1 = []; Array Matching Process - for (const line of source) { const line2Match = target.fi ...

ReactJS: Want to update card design by utilizing the onClick event handler

Currently, I am aware that there will be a need to refactor this code later on to separate things into their own components. However, due to time constraints, I have to wire this up as is at the moment. To achieve this, I utilized array.map() to create car ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Safari experiencing sporadic issues with reCAPTCHA AJAX API within modal dialogs

I am currently utilizing the reCAPTCHA AJAX API to showcase the captcha in a modal dialog box. To display the boxes, I am incorporating jqModal, and opting for the AJAX version of reCAPTCHA due to compatibility issues with the PHP version when used with jq ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

"Rest API is not activating JavaScript on Android devices, whereas it functions correctly in web browsers

<?php $conn = mysqli_connect('localhost','eyukti_home_roc','4nYntQuCjPYR','eyukti_home_roc'); $user_id = $_GET['user_id']; $sql = mysqli_query($conn,"SELECT * FROM `vehicle_type` WHER ...

What could be causing the issue of my CSS file not properly connecting with my HTML files in Django?

I am facing an issue with linking the CSS file to the HTML file in my code. Despite not showing any errors, there is no effect on my webpage. The files I have included are settings.py, base.html, and base.css. Additionally, my static folder is located outs ...

Executing a script for every row in a table using Python and Selenium

As a newcomer to Python and Selenium, I have been struggling with a specific task for days now. Despite my efforts to search and experiment, I find myself completely stuck. My goal is to access sales records within a table that contains information about ...

There seems to be an issue with npm displaying an inaccurate version number for my

In brief: The version of my module on npmjs.org doesn't match the version in package.json. Why? I have a JavaScript module that I released on npm and bower: https://github.com/Offirmo/network-constants.js It has a package.json for npm and a bower.js ...

The filter functionality isn't functioning properly when attempting to filter an array of objects within a Vuex action

I have a collection of objects that is accessed through a getter. I am using this getter inside an action to filter the items, but no matter what I do, the filtering does not seem to work and it ends up returning all the mapped item IDs. filterItems({ gett ...

Implementing the ability to add and remove classes in JavaScript

I am trying to implement an add or remove class feature in JavaScript, but I'm facing some issues with it. Below is the code snippet I have: if (window.location.hash == "#/profile/"){ document.getElementById("tabMenu").removeClass("bottomTa ...

Display the count of ng-repeat items beyond its scope

Currently, I am looping through a list of nested JSON objects in this manner: <div ng-repeat='item in items'> <ul> <li ng-repeat='specific in item'>{{specific}}</li> </ul> </div> I want to ...

Using Key Press to Rotate Messages - Jquery

Need help with rotating an array based on alphanumeric key presses? Check out the code snippet I've been working on below. Unfortunately, I'm having trouble getting the loop to function properly. Any suggestions or feedback would be greatly appre ...

Is Restangular taking forever to resolve the promise?

Just starting out with JavaScript and AngularJS, and this particular issue has me stumped. Requirements A RESTful service that retrieves data from the backend AngularJS 1.2.21 and Restangular 1.4.0 being used An AngularJS controller tasked with requesti ...

The basic evaluation of jQuery elements does not result in a comparison

Wondering what's going wrong in this code: employee_ids = $('[data-employee_id="'+employee+'"]'); timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]'); var common = $.grep(timestamp_ids, function(element) ...

There appears to be a malfunction with certain hyperlinks on the table

There seems to be an issue with the four links in the third column, first, second, third, and fourth rows (Order Form PDF, Rental App PDF, Married Rental PDF, and Consent Form PDF) as they are not functioning properly. Below is the provided code snippet: ...

Firebase issue: The function ref.once is throwing an Uncaught TypeError and is not recognized

I am attempting to utilize Firebase for both uploading a file and storing it in my database simultaneously. I want to track the number of uploads so that I can rename each file uniquely. While I have successfully uploaded and stored a copy in the database, ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Navigate to the final element of a mapped array

My current project includes a Message component that showcases all messages, whether incoming or outgoing, within a single thread. One feature I am aiming to implement involves ensuring that the most recent message, a freshly typed one, or an incoming mes ...

Adapt the CSS based on different screen sizes

I am currently developing a mobile application using angularjs and the ionic framework. My application is intended for both tablet and mobile versions. I have encountered an issue where I cannot use the same CSS for both the tablet and mobile versions. Is ...