Arif Sami Arif Sami - 7 months ago 16
Javascript Question

How to select previous input element outside current div but with same parent div

My HTML code is:

<div id="subjects">
<div class="group">
<label for="n1">1. Name</label>
<div class="child">
<input type="text" name="" id="" />
</div>
</div>
<div class="group">
<label for="n2">2. Name</label>
<div class="child">
<input type="text" name="" id="" />
</div>
</div>
<div class="group">
<label for="n3">3. Name</label>
<div class="child">
<input type="text" name="" id="" />
</div>
</div>
</div>




All I want is if I click second or third input element and if previous one is empty an alert box must be show.

Answer

try this:

$(".required-input").click(function() {
  $($(".required-input").get().reverse()).each(function() {
    if($(this).val() === "") {
      $(this).focus();
      return;
    }
  })
})

and you need to add this custom class on your inputs:

  <div id="subjects">
    <div class="group">
      <label for="n1">1. Name</label>
      <div class="child">
        <input type="text" name="" class="required-input" id="" />
      </div>
    </div>
    <div class="group">
      <label for="n2">2. Name</label>
      <div class="child">
        <input type="text" name="" class="required-input" id="" />
      </div>
    </div>
    <div class="group">
      <label for="n3">3. Name</label>
      <div class="child">
        <input type="text" name="" class="required-input" id="" />
      </div>
    </div>
  </div>

Plunker: https://plnkr.co/edit/FFhA4ttec7TeOPbUtH6o?p=preview