php – How to disable a text field for editing using jQuery/JavaScript?

Question:

Let's say I have a form with fields 1 through 7.

Something like:

field-1
field-2
field-3
field-4
field-5
field-6
field-7

All these fields are on one form.

With Laravel, I've sometimes experienced situations where when I disable a field with the disabled property, I haven't been able to retrieve it via the Input array. So, to directly avoid this problem I would like to know if there is, and if there is, how, a way to block, via JS/jQuery, that a field is edited in the form. HOWEVER, I will only know this (whether it should be disabled or not) at runtime.

Ex.: According to the field-2 value I may need to disable the field-3 , field-4 and field-5 for editing, but I will still need their values ​​in the INPUT array, which will be assigned to have the same field-2 value in this case.

I don't know if I managed to be clear, but any questions ask in the comments!

Answer:

The browser doesn't send disabled fields with disabled on form submission, so your first attempt didn't work.

On the other hand, you don't need to use script to prevent changing a field. Instead, use the readonly attribute.

Side effects:

  • The user can, however, click and select the field content.

  • Also, the styles of the field will remain the original ones, that is, the user may not realize that this is a read-only field. In that case, add a styling to maintain usability, for example, leaving the bottom of the box a little greyed out.

Example:

<input type="text" value="Valor fixo" 
    style="background: #EEE; cursor: not-allowed; color: #777" readonly />

CSS Class Example for Reuse:

.desabilitado {
    background: #EEE; 
    cursor: not-allowed; 
    color: #777;
}

That way you can keep visual feedback to the user.

See the working example of the code above in jsfiddle .

security considerations

One could argue that disabling fields on the screen is not a good practice from an Information Security point of view, as today a user can easily bypass this limitation through the Developer Tool ( F12 ) by changing the field's properties. This is partly correct.

The important thing is to understand that the need to disable fields is an essential part of the systems functioning. It is not its purpose to ensure the security of information in that field.

This article is intended to assist the front-end developer with a purely visual element and does not exempt the necessary validations on the back-end .

Scroll to Top