Dreagen
Dreagen

Reputation: 1743

Disable a input field so "getElementById(field_name).value =" will no longer change its value

I have an input field which is disabled or not based on its contents. However I also have a button which changes the value of this field using the javascript getElementById('field_name').value = "something".

Is it possible to have it so that this will not change the value of the field if it is disabled?
I have tried both setting the field to readonly and disabled, but this doesn't stop the button from changing its value

Upvotes: 1

Views: 355

Answers (3)

sgowd
sgowd

Reputation: 2262

Try something like this-

if(!getElementById(field_name).disabled){
          getElementById(field_name).value = "something";
 }

Upvotes: 0

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263117

The simplest way is probably to perform the check in your button's click handler.

Instead of doing:

document.getElementById("field_name").value = "something";

Do:

var element = document.getElementById("field_name");
if (!element.disabled) {
    element.value = "something";
}

Upvotes: 1

Jon
Jon

Reputation: 437734

If you want to have the setting code to respect the disabled attribute, simply make it so:

var el = getElementById('field_name');
if (!el.disabled) el.value = "something";

Upvotes: 0

Related Questions