1

I have the following two fields on an HTML form:

<input type="hidden" name="Valid" id="Valid" value="True">

<input type="text" id="Address">

I need a JavaScript method that will disable the address input if the value of the valid input is true.

What can I use to do this, please?

I think I need a way of toggling disabled on the Address input form.

TechySharnav
  • 4,869
  • 2
  • 11
  • 29
dstewart101
  • 1,084
  • 1
  • 16
  • 38

2 Answers2

1

You can define a "onchange"-event, which triggers when the value of that hidden input changes. Here is an example of that: Does HTML Hidden control have any events? Like onchange or something?

But from reading the comments, that wasn't needed at all :-)

What is needed, is a logic which runs on page-load. Your function only needs to add the disabled-attribute to the field, when the valid-value is true.

<input type="hidden" name="Valid" id="Valid" value="True">


<script>
// Define your function
function yourfunc() {
    var validValue = document.getElementById("Valid").getAttribute('value');
    if(validValue == 'True') {
        document.getElementById("Address").setAttribute('disabled', true);
    }
}
yourfunc(); // Call the function: is important, otherwise your code will never be run.
</script>

To remove the disabled-property again, you can check this thread: .setAttribute("disabled", false); changes editable attribute to false

Visionstar
  • 355
  • 2
  • 12
  • Thanks for coming back so quickly. The value of `valid` won't change. It is being worked out backend, and by the time the page loads the value will be fixed at true or false. – dstewart101 Jun 04 '21 at 07:34
  • When should the value of valid change? You didn't specify anything yet for the change of #Valid – Visionstar Jun 04 '21 at 07:37
  • at the point when the page loads the valid will be true or false and will stay that way. for the sake of this question, let's say it's always true. thanks – dstewart101 Jun 04 '21 at 07:40
  • 1
    oh - that's a completly different use case; i edited my answer accordingly to this information. Please check again. – Visionstar Jun 04 '21 at 07:43
1

I need a javascript method that will disable the address input if the value of the valid input is true.

Based on this line alone, the below code should work

const validInput = document.querySelector('#Valid');
const addressInput = document.querySelector('#Address')

const toggleAddress = () => {
    const inputVal = validInput.value;
    
    if(inputVal === 'True') {
            addressInput.disabled = true
    }
}

toggleAddress()

Although your question doesn't say when it should be enabled.

PushpakB
  • 11
  • 1
  • thanks for this. this would work for me - i have marked the first response as the answer as that is the one i have used. – dstewart101 Jun 04 '21 at 08:45