Alain D'scoux
Alain D'scoux

Reputation: 33

jquery uncheck change value incremented input

this question is over my skill.

If I uncheck checkbox 3, I want to change the value of input 3, 4, 5, 6, 7, 8, 9.
If I uncheck checkbox 6, I want to change the value of input 6, 7, 8, 9.
If I uncheck check X, I want to change the value of input X++.

I wrote this jquery code :

<code>
$('input[type=checkbox][name=checkbox_5]').on('change', function () {
  if ($(this).is(":not(:checked)")) {
      $('input[type=text][name=input_5]').val('');
      $('input[type=text][name=input_6]').val('');
      $('input[type=text][name=input_7]').val('');
      $('input[type=text][name=input_8]').val('');
      $('input[type=text][name=input_9]').val('');
  }
});
</code>

I have 9 checkbox. I don't want to wrote for each checkbox this snippet. Can you help me to fix this ?

I prefer to use increment, but I don't know how to do it.

https://jsfiddle.net/j4q6jm6u/

Upvotes: 2

Views: 150

Answers (1)

Kld
Kld

Reputation: 7068

You can use .index() to get the index of the clicked checkbox then change the value of text fields with index greater than it with :gt()

 
$('input[type=checkbox]').on('change', function () {
  var index = $( "input[type=checkbox]" ).index( this );
  console.log(index)
  if ($(this).is(":not(:checked)")) {    
      $('input[type=text]:gt('+index+')').val('');     
  }else {
     $('input[type=text]:gt('+index+')').val(index);  
  }
});
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>

<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">

Upvotes: 1

Related Questions