Ingus
Ingus

Reputation: 1044

Disable only unwanted inputs Javascript

I have this cool piece of Javascript that disables rows and change color were input is disabled.

But I need:
If filled input #1 all other 3 inputs are disabled,
if filled input #3 all other 3 inputs are disabled,
if filled input #2 and/or #4 then inputs #1 AND #3 are disabled.
Data is coming from database.

Javascript:

$(".input").on("keypress change keyup",function(){
   if($(this).val() != "")
   {
     $(this).parent().parent().find(".input").not($(this)).prop("disabled",true).css("background-color","#cccccc");  
   }
   else
   {         $(this).parent().parent().find(".input").prop("disabled",false).css("background-color","#ffffff");
   }
});

And here is the table code:

<table>
  <tr>
    <td>
      <input type="text" class="input" value="">
    </td>
    <td>
      <input type="text" class="input" value="">
    </td>
    <td>
      <input type="text" class="input" value="">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" class="input" value="">
    </td>
    <td>
      <input type="text" class="input" value="">
    </td>
    <td>
      <input type="text" class="input" value="">
    </td>
  </tr>
  </table>

This piece of code was made by Alexis.

Upvotes: 0

Views: 82

Answers (1)

Alexander Holman
Alexander Holman

Reputation: 929

Here are the codes you seek...

HTML

To avoid the issue you were having with hidden inputs etc and not knowing the nth-term of each element, use classes instead:

<table>
  <tr>
    <td>
      <input type="hidden" class="input" value="">
    </td>
    <td>
      <input type="text" class="input toggle all" value="">
    </td>
    <td>
      <input type="text" class="input toggle every-other" value="">
    </td>
    <td>
      <input type="text" class="input toggle all" value="">
    </td>
    <td>
      <input type="text" class="input toggle every-other" value="">
    </td>
  </tr>
</table>

JQuery

$('body').on( 'keyup blur', '.input.toggle', function() {
    var $this = $( this );
    var $parent = $this.parent();
    var $disable = $parent.siblings().children();
    if ( $this.val() != "" )
    {
              if ( $this.is( '.all' ) )
                {
                      $disable = $parent.siblings().children( '.toggle' );
                }
              else if ( $this.is( '.every-other' ) )
                {
                      $disable = $parent.siblings().children( '.all' );
                }
              $disable.attr( 'disabled', true ).css("background-color","#ccc");
    }
    else
    {
        $disable.removeAttr('disabled').css("background-color","#fff");
    }
});

And here is an example of it working.

Upvotes: 1

Related Questions