Hide Button When Input Value Is Empty or N/A

I’d like to hide the corresponding button when an input value is empty or has a value=“n/a”.

In the following example, the input box “boat” is corresponding with the button “button_boat”, and the input box “car” with the button “button_car”, and the input box “dog” with the button “button_dog”.

Note: you cannot change the properties of the input element with type=“text”.


  <div>
    <form action="">
      <fieldset>
        <input type="text" name="boat" id="boat" disabled="disabled" value="n/a">
        <input type="text" name="car" id="car" disabled="disabled" value="2">
        <input type="text" name="dog" id="dog" disabled="disabled" value="">
      </fieldset>
    </form>
  </div>

  <div>
    <div id="button_boat"><input type="button" value="Boat"/></div>
    <div id="button_car"><input type="button" value="Car"/></div>
    <div id="button_dog"><input type="button" value="Dog"/></div>
  </div>

Without script the output will look like this:

With script the output will look like this:

Anyone know a Javascript that can do this?

Sure. Here’s a way to do it:


.hidden {
    display: none;
}


var form = document.getElementById('numberOfItems'),
    inputs = form.getElementsByTagName('input'),
    i,
    input,
    id,
    button;

for (i = 0; i < inputs.length; i += 1) {
    input = inputs[i];
    id = 'button_' + input.id;
    button = document.getElementById(id);
    button.className = 'hidden';
    if (input.value !== 'n/a' && input.value > '') {
        button.className = '';
    }
}

The code works nicely, thanks!

I was wondering, could this also work without id = ‘button_’ + input.id

For example if you have the following html code:


  <div>
    <form id="numberOfItems" action="">
      <fieldset>
        <input type="text" id="boat" disabled="disabled" value="n/a">
        <input type="text" id="car" disabled="disabled" value="2">
        <input type="text" id="dog" disabled="disabled" value="">
      </fieldset>
    </form>
  </div>

  <div>
    <div id="sail"><input type="button" value="Boat"/></div>
    <div id="drive"><input type="button" value="Car"/></div>
    <div id="walk"><input type="button" value="Dog"/></div>
  </div>

However you cannot change the html code manually.
What needs to be changed to the javascript to accomplish the same result?

You have a couple of different options there.

You could create an array that specifies the relationship between ship and sail, and for the other ones there too.
Or, you could loop through each div and compare the input field id with the value of the button.

I see where your going at, but I’m afraid this will also conflict with some other code on my page. So I tried something else instead. Can’t post it here though, it’s an completely different solution.

Thanks for the help anyways! :slight_smile: