JQuery - select empty text input and add border for them

I want to add border for empty text input fields. So I wrote the following code. But it doesn't work. So I used the alert box to see how many selectors were selected. But it returns 0. What is my mistake?

 $("input[type=submit]").click(function(){
       var empty = $('input:text[value=""]');
       alert(empty.length);

       if(empty.length >0){

           $("form").effect("shake",{
               times:3,
               distance : 50         

           },450,function(){
           $('input:text[value=""]').each(function(){
              $(this).css("border","1px solid red"); 
           });
           });



           return false;
       }

   });

      

+3


source to share


2 answers


Try to use .filter()

for this purpose, the value attribute will not be affected when the value in it changes.



$('input:text').filter(function(){
   return $.trim(this.value).length == 0;
}).css("border","1px solid red");

      

+6


source


Try the following:

$("input[type=submit]").click(function(){
    var isShake = 0;
    $('input:text').filter(function(){
        if ($.trim(this.value).length == 0){
            isShake = 1;
            $(this).css("border","1px solid red");
        }else{
            $(this).css("border","1px solid black");
        }           
    });

    if(isShake){
        alert('Shake Effect or something like');
    }
});

      



Check out JSFiddle demo

+1


source







All Articles