The getElementById method for validating input length is malfunctioning

function validateInput(input) {
  var text = document.getElementById('t').value;
  if(document.calculator.t.value.length == 10) {
    alert("Invalid length - only 10 characters allowed!");
  }
  if(text.length > 10) {
    alert("Invalid length - only 10 characters allowed!");
  }
}
<form name="calculator">
  <input type="text" maxlength="10" name="answer" id="t" onkeyup="isAllowedSymbol(this);validateInput(this); " placeholder="Enter data" >
  <br />
  <input type="button" value=" 1 " onclick="calculator.answer.value += '1'" />
  <input type="button" value=" 2 " onclick="calculator.answer.value += '2'" />
  <input type="button" value=" 3 " onclick="calculator.answer.value += '3'" />
  <input type="button" value=" + " onclick="calculator.answer.value += '+'" />
  <input type="button" value=" exp " onclick="calculator.answer.value = Math.exp(calculator.answer.value);" />
  <br />
  <input type="button" value=" 4 " onclick="calculator.answer.value += '4'" />
  <input type="button" value=" 5 " onclick="calculator.answer.value += '5'" />
  <input type="button" value=" 6 " onclick="calculator.answer.value += '6'" />
  <input type="button" value=" - " onclick="calculator.answer.value += '-'" />
  <input type="button" value=" ln "  onclick="calculator.answer.value = Math.log(calculator.answer.value);" /> 
  <br />
  <input type="button" value=" 7 " onclick="calculator.answer.value += '7'" />
  <input type="button" value=" 8 " onclick="calculator.answer.value += '8'" />
  <input type="button" value=" 9 " onclick="calculator.answer.value += '9'" />
  <input type="button" value=" &#215; " onclick="calculator.answer.value += '*'" />
  <input type="button" value=" &#8730; " onclick="sqrt(calculator.answer.value)" />
  <br />
  <input type="button" value=" C " onclick="calculator.answer.value = ''" />
  <input type="button" value=" 0 " onclick="calculator.answer.value += '0'" />
  <input type="button" value=" = " onclick="calculator.answer.value = eval(calculator.answer.value)" />
  <input type="button" value=" &#247; " onclick="div(calculator.answer.value)"/>
  <input type="button" value=" x&#178; " onclick="sqr(calculator.answer.value)" />
  <br />
  <input type="button" value=" cos " onclick="calculator.answer.value = Math.cos(calculator.answer.value);" /> 
  <input type="button" value=" sin " onclick="calculator.answer.value = Math.sin(calculator.answer.value);" />
  <input type="button" value=" tan " onclick="calculator.answer.value = Math.tan(calculator.answer.value);" />
  <input type="button" value=" . " onclick=" "; />
  <input type="button" value=" &larr; " onclick="backspace(calculator.answer.value);"; />
  <p align=right>&#8226; &#169;</p>
</form>

I am developing my first calculator and encountering an issue. The validation for input via the keyboard is working correctly (not allowing more than 10 characters), but for inputs through buttons it's not... what could be causing this problem? Am I doing something wrong with my maxlength="10" attribute?

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

Answer №1

When you type in the box, the length is checked on the onkeyup event, but it does not happen when buttons are clicked.

A solution to this issue would be to check the length on the onchange event instead.


Latest Update:

To ensure that the fix works correctly, you need to manually trigger the onchange event because changing the value property does not automatically dispatch it.

JavaScript:

calculator.answer.value += '0';
calculator.answer.onchange();

Alternatively, a more efficient approach would be:

JavaScript:

if ("createEvent" in document) {
    var evt = document.createEvent('HTMLEvents');
    evt.initEvent('change', false, true);
    calculator.answer.dispatchEvent(evt);
}
else
    calculator.answer.fireEvent('onchange');

If the handler becomes too complex, consider creating a generic handler for your buttons rather than using inline commands.

Answer №2

It appears that the values being inputted via keyboard are being validated, while those entered using buttons are not. The reason for this discrepancy is that you are attaching the checking function to the onkeyup event, which only triggers after a key has been pressed and released within the input field. To ensure consistent validation for all inputs, consider binding your function to the onchange event instead.

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

Issue with ng-checked not detecting boolean values retrieved from local storage

I'm working on a code snippet in my controller where I have a checkbox in my HTML with "ng-checked="enterToSend" and "ng-click="enterToSendCheck()" attached to it. $scope.enterToSend = localStorage.getItem('enterToSend'); $scope.enterToSen ...

How to Implement a Dropdown Menu in HTML and CSS for Navigation Bars

Currently, I am in the process of creating a website at www.bossfakeid.co.uk. I am looking to add a dropdown menu to the "Products" section of the navbar. I found a dropdown menu solution that I would like to implement from this link: http://codepen.io/wil ...

Create a notification menu in Bootstrap using Bootply, which conveniently displays a numerical badge at the top

I am interested in implementing a bootstrap notification menu similar to the one found at this link: http://www.bootply.com/oasBuRC8Kz# However, I would like to add the number of notifications to the upper right corner of the glyphicon. I have gone throug ...

I'm experiencing difficulties with app.use() not functioning in my specific case, even though the paths are identical

My goal is to transfer the dist folder from the server to the client. When I use the following command, it works perfectly: app.use('/', express.static( Path.join(__dirname, '..', 'node_modules', 'del-js-webapp', &a ...

Adjusting the alignment of button text in an Angular Kendo grid

I am currently utilizing the grid view feature of Kendo UI for Angular. While I have buttons on the grid, the issue is that the text within the buttons is not centered properly despite applying styles such as text-align:center. Here is the template for my ...

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

Comparison of Uint8Array and Uint8ClampedArray

Can you explain the distinction between Uint8Array and Uint8ClampedArray within JavaScript? I've heard that Uint8ClampedArray is specifically utilized for pixel manipulations on canvas. Could you elaborate on why this array type is recommended for suc ...

Guide on darkening the surrounding div of an alert to give it a modal-like effect

I want to display an alert to the user in a visually appealing way. To achieve this, I am utilizing Bootstrap's alert class. Here is how I am showing the user a div: <div class="alert alert-warning alert-dismissible" role="alert"> Some text ...

Struggling with Input Padding Across Different Browsers?

I am facing an issue with my search form that is supposed to look like this: </p> This is the sample HTML code for the search form: <form method="post" action="#" class="search-form"> <input type="text" class="nav-search-input input ...

Assistance with updating an array in MongoDB is required

I've come across a challenge with my document collection: { _id: 1, name: 'xpto', arr: [1, 2, 3] }, { _id: 2, name: 'xyz' } My goal is to add number 4 to the "arr" array using $addToSet and update {multi: 1}, but I e ...

Passing Data from Next.js Middleware to getServerSideProps during the Initial Request with the Help of Cookies

Encountering a challenge within a Next.js application (for a coding challenge). Requested flow to achieve: Check for geolocation cookie in Next middleware. If not present, fetch data and store in cookie. In getServerSideProps, utilize the cookie (if avai ...

Incorporate a prefix into the URL of Angular development servers

When our application is in production, it will not be served from the root. Instead, it will be served from something like https://ourdomain.com/ourapp. This setup is causing problems with image URLs. To work around this issue, I am trying to serve the ap ...

What is the best way to create a JavaScript function that can receive and "pass along" a varying number of parameters?

Is there a way to create a Javascript function that can accept a variable number of parameters and pass them on to other anonymous functions? Let's consider an example scenario where a method needs to trigger an event: function fireStartedEvent(a,b, ...

What is the best way to programmatically insert values into a JavaScript object?

Currently, I am delving into the world of Angular and have come across an example code snippet that looks like this: $scope.contents = [{ name: 'Chris Doe', abbreviation: 'Developer', },{ name: 'Ann Doe', abb ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...

sudden swivel when shifting camera while following an object on a flat surface/pathway

I'm relatively new to three.js and I'm eager to create a scenario where a cube or object moves on a flat surface or road. I have managed to move the object in the z direction, but now I want to move the camera as well, giving the impression of a ...

Maintaining the position of an image during animation movements

I am experiencing an issue with a grid of images where, upon clicking one image, all the other images move down. However, the remaining image is pulled to the top left corner. I suspect this is happening because by removing the other images, the remaining ...

Ways to guarantee that a function is executed only once within an object notation

Although there are numerous techniques available on Stack Overflow to ensure a function is only called once, none of them seem to fit my specific scenario and objectives. In this case, the function is nested within an object literal, and I aim to either ad ...

Refresh a partial view in Rails using AJAX with JSON feedback

Whenever I make a call to $.getJSON, my goal is to refresh the tbody elements. This means that I need to remove all current elements and replace them with new elements based on the JSON response. Javascript $(document).ready(function(){ $('#positi ...

Can you show me the steps for linking the next method of an EventEmitter?

After emitting an event, I am looking to run some additional code. Is there a method to chain the .next() function in this way? @Output() myEvent = new EventEmitter<string>(); this.myEvent.next({‘test string’}).onComplete(console.log('done& ...