Yoong Tat Yoong Tat - 21 days ago 6
Javascript Question

Enable/Disable Form by Input

I have two input forms. When they are loaded into the browser with default values, the forms are disabled.

I have created a script function that enables the input forms

onclick
. The user can then change the values in either of those 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 here is that both the input values must not equal the default value for the forms to remain enabled. I'm struggling to fix this.



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.