简体   繁体   中英

How to get a previous element to another using jQuery?

I want to do this.

<p class="validator">This is an error!</p>
<input type="text" validator="isGoodValue" value=""/>

<p class="validator">This is an error 2!</p>
<label>
<input type="text" validator="isGoodValue" value=""/></label>

<div><p class="validator">This is an error 3!</p></div>
<label>
<input type="text" validator="isGoodValue" value=""/></label>    

<script>
$('input').change( function() {
 if (!isGoogValue( $(this).val() )) {
     $(this).GET_ME_THE_VALIDATOR_ABOVE_ME().show();
 }
 else {
     $(this).GET_ME_THE_VALIDATOR_ABOVE_ME().hide();
 }
});
</script>

What may be the code of GET_ME_THE_VALIDATOR_ABOVE_ME to get the exactly

validator above, independent of HTML structure? or What function of jQuery do this work...???

I'm trying to use closest, parent, prev.. but that doesn't works well.

Try this

 if (!isGoogValue( $(this).val() )) {
     $(this).prevAll('.validator:first').show();
 }
 else {
     $(this).prevAll('.validator:first').hide();
 }  

The real solution is to have some consistent structure so that you error messages aren't completely disconnected from your inputs and then you can use a solution similar to what Anton suggests.

Alternatively, if it's absolutely impossible to restructure your HTML to something sane, you could give IDs to all your inputs and IDs to your error messages that can be related somehow. For example, input 1 has an ID of input1 , and it's corresponding error is input1error . Then you can do something like this:

$('input').change( function() {
     if (!isGoodValue( $(this).val() )) {
         var id = $(this).attr("id");
         $("#" + id + "error").show();
     }
     else {
         var id = $(this).attr("id");
         $("#" + id + "error").hide();
     }
 }); 

See this fiddle .

Now it doesn't matter where your errors appear, so long as they can be related via their ids somehow.

Another solution show in this fiddle assumes that the nth input corresponds to the nth validator like this:

$('input').each(function(index, elem) {
    var idx = index;
    $(elem).change(function() {
        var val = $('.validator').eq(idx);
        if (!isGoodValue( $(this).val() )) {
            val.show();                
        }
        else {
            val.hide();
        }
    });            
});        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM