开发者

Apply Class on load

I want to apply the following style ='position: relative; left: 42px;' to the label if value of the textbox is empty. and onfocus this style has to be removed

<lab开发者_开发问答el for'13321'>Name</label><input type='text' id='13321' class='box'>
<label for'14422'>Name</label><input type='text' id='14422' class='box'>


Put the style into a class, say yourClass, and then you can use the following:

$(function() {
    $('input.box').filter(function() {
         return $(this).val() === "";
    })
    .prev('label')   // go to label
      .addClass('yourClass')
    .end()    // back to input
    .one('focus', function() {
         $(this).prev('label').removeClass('yourClass');
    });
});

or without filter (you have to test what is more performant):

 $('input.box:not([value]), input.box[value=""]')
   .prev('label')
     .addClass('yourClass')
   .end()
   .one(...

Edit: I missed that you want to add the class to the label. Fixed.

Update: If you want to reapply the class, in case the value stays empty, you have add a blur listener and use focus instead of one above:

.focus(function() {
    $(this).prev('label').removeClass('yourClass');
})
.blur(function() {
    if($(this).val() === "") {
        $(this).prev('label').addClass('yourClass');
    }
})


css

.empty{
    position: relative; left: 42px;        
}

js

  $(function() {
      $(":input:text").each(function(){
         if( $(this).val() == "")
         {
             $(this).prev("label").addClass("empty");
             $(this).focus(function(){
                     $(this).prev("label").removeClass("empty");
                 })
         }
      });
   });

demo

http://jsfiddle.net/jURc9/13/


Jquery:

$(document).ready(function(){
$('input.box').each(function(){
   if($(this).val()=="") {
       $(this).addClass('new-class');
   }
})
   $('input.box').focus(function(){
       $(this).removeClass('new-class')
   })
})

CSS:

.new-class {
   position: relative;
   left: 42px;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜