Yoong Tat Yoong Tat - 23 days ago 5
HTML Question

Enable and Disable Form Input depending on input value

This is my requirement:
I have 2 input forms, lets call them A and B

A and B are loaded into the browser with default values, and the forms are disabled by default.

I have created a javascript function that enables the input forms on click.

Here is the test code i have written so far.
The user can then change the values in either forms.
As long as the value in any of the form is not the default value, both forms must remain enabled.
If the user changes both the value in the input form so that it is back to its default value, then the forms will be disabled automatically again.

The problem with this code is that both the input form values must not equal to the default value for the forms to remain enabled. I have tried fiddling around with break; but to no luck



function enable() {
var x = document.getElementsByClassName("row")
for (i = 0; i < x.length; i++) {
x[i].disabled = false;
}
}

var x = document.getElementsByClassName("row")

function check() {
for (i = 0; i < x.length; i++) {
if (x[i].value == x[i].defaultValue) {
for (i = 0; i < x.length; i++) {
x[i].disabled = true;
}
}
}
}

<table>
<tr>
<td onclick="enable()">
<input class="row" type="text" value="click me" disabled onblur="check()">
<input class="row" type="text" value="click me2" disabled onblur="check()">
</td>
</tr>
</table>




Answer

function enable() {
  var x = document.getElementsByClassName("row")
  for (i = 0; i < x.length; i++) {
    x[i].disabled = false;
  }
}

var x = document.getElementsByClassName("row")

function check() {
  var edited=false;
  for (i = 0; i < x.length; i++) {
    if (x[i].value != x[i].defaultValue) {
      edited=true;
    }
  }
  if(edited)return;
  for(i=0; i<x.length; i++){
     x[i].disabled=true;
  }
}
<table>
  <tr>
    <td onclick="enable()">
      <input class="row" type="text" value="click me" disabled onblur="check()">
      <input class="row" type="text" value="click me2" disabled onblur="check()">
    </td>
  </tr>
</table>

So you mean something like this?

EDIT: So what we do is create a boolean which will keep track of any changes. You did some strange things with nested loops, which isn't really necessary. If there is a change detected, edited will be true. If they are both the same, the default value of edited will be used (false).

After the first for-loop, we check if edits have been made if(edited) If an edited has been made, we use return to break out of the function. You could also use:

if(!edited){
    for(i=0; i<x.length; i++){
         x[i].disabled=true;
    }
}

But I think using return is a bit cleaner. So if no edits have been made (the default value is entered), the code will continue and disable all fields.