How to reset a disabled form field using JavaScript

I think I know the answer to think, but just wanted to test my logic on more experienced folk.

I have a series of form fields/inputs being used to accept numbers for a calculation. Three of the four are open to user input, whilst the fourth is of a fixed value that the user cannot change.

On navigating to the page, all inputs contain a set of default values as configured using the <input value=""> attribute in the HTML which works fine. What I’m trying to protect against though, is a user playing around with the values in the browser dev tools, particularly where no value is set, which (sticking to purely to numbers for the purpose of the calculation) feeds NaN into my calculation.

I can protect against that for the purposes of the calculation itself, but less so for the reset button - because the input is disabled, JavaScript isn’t able to apply the chosen fixed default value.

What I think I have to do is as follows when the reset button is clicked:

  1. Use JS to turn the disabled attribute off
  2. Reset to the correct value
  3. Turn the disabled attribute on again.

Does this make sense, or is there a better way of doing it?

You can’t prevent people from changing the client-side code in dev tools. Is there a particular side effect on the server that this is causing which you need to prevent instead?

I’m well aware that I can’t prevent that in the browser. There is no server side where this calculation is concerned, as the output is purely intended as ‘indicative’ information to the user. All I’m trying to do is ensure that when the reset button is clicked, that all inputs are restored to their intended values, regardless of how they may have come to be altered.

ah… ok. That can be done.

Well resetting a form will set an input’s value property to its defaultValue property, which is the same as its current value attribute – this has nothing to do with the input being disabled or not. So if you initially store the original value in a JS variable, you don’t have to un-disable it either to restore that value.

I don’t think there’s a better way… maybe more esoteric ways though such as watching for attribute changes with a mutation observer and immediately restoring the old value. ^^ Also you can always hijack any function during runtime with the debugger, so there is no bullet-proof solution AFAICT.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.