Home > Blockchain >  How to reference a sibling of a non-trigger element using jQuery?
How to reference a sibling of a non-trigger element using jQuery?

Time:04-05

I am using the jQuery below to validate an input field on click of '#button' and show an alert if the input is empty. However I'd like to do the same for multiple other inputs and would like to avoid creating unique IDs and duplicating this code for each one, because there are a lot.

<script>
$('#button').click(function(e) {
     
if ($('#input').val().length !=0){
   $('#alert').hide();
} else {
   $("#alert").show();
}
});
</script>
.alert {
display: none;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>


<input type="text" id="input1" name="fname"><br>
<p  id="alert">This field is required</p>

<input type="text" id="input2" name="lname"><br><br>
<p  id="alert">This field is required</p>
 
<input type="button" id="button" value="Submit">

The alert element is a sibling of the input, so one way I am thinking it may be possible to target each input/alert independently is by referencing the alert as a sibling of the input, e.g. something like below, but this only references siblings of the trigger button, not siblings of the input as intended. How can this be achieved?

$(this).siblings('#alert').show();

CodePudding user response:

$('#button').click(function(e) {
  $('input').each((i,x)=>{
    let v=$(x).val();
    let a=$(x).closest(".input-group").find(".alert");
    if(v==undefined || v==null || v=="")
      $(a).show();
    else
      $(a).hide();
  });
});
.alert {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div >
  <input type="text" id="input1" name="fname"/>
  <span  id="alert">This field is required</span>
</div>

<div >
  <input type="text" id="input2" name="lname"/>
  <span  id="alert">This field is required</span>
</div>

<input type="button" id="button" value="Submit"/>

  • Related