sdfgg45 sdfgg45 - 17 days ago 5
jQuery Question

How to dynamicaly navigate/find element to trigger another element jQuery?

I have a input field and when it updates i want to another one to show up.
In this case its simple, but if i have 100 html rows like this, i can't rely on the simple version, example below:

<div class="row">
<div class="col-md-6">
<label>Test</label>
<input type="text" class="form-control test" name="test">
</div>
<div class="col-md-6">
<label>Test2</label>
<input type="text" class="form-control test2" name="test">
</div>
</div>

Simple example:

$('.test2').fadeIn(500);


Instead of this i need a more dynamic solution, this is just how i imagine it would be, but a working example is appreciated.

<script>
$('.test2').hide();

if($('.test')).change(function(){
$(this).prev('div').closest('.test2').fadeIn(500);
});
</script>

Answer

After adding test2 class to your second input, this works this way

$('.test2').closest("div").hide();
$('.test').change(function() {
  $(".test2", $(this).closest('.row')).closest("div").fadeIn(500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-6">
    <label>Test</label>
    <input type="text" class="form-control test" name="test">
  </div>
  <div class="col-md-6">
    <label>Test2</label>
    <input type="text" class="form-control test2" name="test">
  </div>
</div>

Comments