开发者

Getting the right object references in jQuery to make validation work

I have a form in my admin panel and am having a bit of trouble with my references in jQuery.

The form code looks like this:

<div class="full-width">
    <label for="file_name-644" >File Name</label> 
    <span class="relative"><input type="text" name="file_name-644" id="file_name-644" class="full-width" disabled="disabled" value="pic.jpg"/><span ></span></span>
</div>
<div class="full-width">
    <label for="name-644" class="required">Name</label> 
    <span class="relative"><input type="text" name="name-644" id="name" value="" class="full-width name"/><span ></span></span>
</div>

now, as this form can have multiple entries processed at once, the numbers will change on the references (so from 644 to 108 for example). This is created with a php loop.

In jquery i'm using an .each() loop to check that the values are filled. Right now, all I need for validation is non-empty fields for the name. Currently, it looks like this:

$('.name').each(function(开发者_JAVA百科index) {
    if(!$(this).val()){ctr++;}else{error++;}
});

The variables ctr and error are counters that I later use to point out errors or how many entries are ready to be processed.

What I want to add to this is a change to the label for just the entries that are empty so that these stand out. I know I can change all of them with

$('.required').css({'color': '#AB1414'}); but how can I do this in the .each() loop above and just for the empty values?

Thanks in advance!


To use the .each() loop in your code, you could do the following. Note that it uses jQuery.trim()(docs) to consider values with only white space to be empty as well.

Using prev()(docs) it also gets the previous <label> of its parent()(docs) , but only if it has the required class. Then in the if(), it checks the length(docs) property of the <label> object to see if there indeed was a required label.

$('.name').each(function(index) {
    var $th = $(this);
    if( $th.parent().prev('.required').length && !$.trim( $th.val() ) ){ctr++;}else{error++;}
});


You need to add required class for input fields rather than span and use this code on validation

 $('.required').each(function(){
       if ($(this).val() == '') $(this).css({'color': '#AB1414'});
    });


Maybe try this for HTML:

<div class="full-width nameContainer">
    <label for="name-644" class="required">Name</label> 
    <span class="relative"><input type="text" name="name-644" id="name" value="" class="full-width name"/><span ></span></span>
</div>

And for JS:

$('.nameContainer').each(function(index) {
    var value = $(".name", this).val();
    if(!value)
    {
      $('.required', this).css({'color': '#AB1414'});
      ctr++;
    }
    else
    {
      error++;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜