Lucfia Lucfia - 5 months ago 25
jQuery Question

Trigger next submit button

I am having problem with selecting the next submit button via jQuery.

I have something like this:



$('.description-part').on('change', 'textarea', function() {
$(this).find('.button').addClass('test'); // not working
$(this).next('.button').addClass('test'); // not working
$(this).closest('.button').addClass('test'); // not working
});

<div class="description-part">
...
<textarea></textarea>
<div></div>
<input type="submit" name="save" class="button">
...
</div>




Answer

Just use the nextAll() as the this is textarea and not div and you have a <div> in between the textarea and button, so .next() won't work either:

$('.description-part').on('change', 'textarea', function() {
    $(this).nextAll('.button').addClass('test');
});

Or you can use .closest() this way:

$('.description-part').on('change', 'textarea', function() {
    $(this).closest('.description-part').find('.button').addClass('test');
});

Working Snippet

$(function() {
  $('.description-part').on('change', 'textarea', function() {
    $(this).closest('.description-part').find('.button').addClass('test');
  });
});
.test {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="description-part">
  ...
  <textarea></textarea>
  <div></div>
  <input type="submit" name="save" class="button" />...
</div>

$(function() {
  $('.description-part').on('change', 'textarea', function() {
    $(this).nextAll('.button').addClass('test');
  });
});
.test {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="description-part">
  ...
  <textarea></textarea>
  <div></div>
  <input type="submit" name="save" class="button" />...
</div>