0

I have a text box in which value is 0 when page loads and I want if there is a 0 value in any numeric box, I want its background color to be changed on page load.

I want to do it using jquery only.

My code for this is not working, please find the demo link below and suggest on mistakes.

http://jsfiddle.net/ph43cuhj/1/

Below is my code:

$(document).ready(function(){
    if($("input:text").val()=='0')
        $(this).css('background-color','#c0c0c0');
});
1
  • You have to use a loop to select each input, because currently, $(this) is undefined... Commented Sep 9, 2014 at 7:50

4 Answers 4

2

Use

$(document).ready(function () {
    $("input:text").change(function () { //Bind change vent
        if ($(this).val() == '0') {
            $(this).css('background-color', '#c0c0c0');
        }else{
            $(this).css('background-color', '');
        }
    }).change(); //Trigger initally
});

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

why we have used .change() for this?
@Vaibhav, To trigger when page loads
1

Try this :

$(document).ready(function(){
  $('input[type="text"]').each(function(){
    if( $(this).val() == '0' )
    { 
       $(this).css('background-color','#c0c0c0'); 
    }
  });
});

DEMO

EDIT :-

OR Try This :

$(document).ready(function(){
    $('input:text').each(function(){
        if( $(this).val() == '0' )
        { 
           $(this).css('background-color','#c0c0c0'); 
        }
    });
});

DEMO

Comments

0

More compact:

$(document).ready(function () {
    $('input[type="text"][value="0"]').each(function () {
         $(this).css('background-color','#f00'); 
    });
});

Comments

0
for(i=0;i<$("body").find("input:text").length;i++)
 {
   var el=$("body").find("input:text").eq(i);
   if(el.val()==0){  el.css('background-color', '#c0c0c0');   }
   else  { el.css('background-color', '#000000');    }
}

try this code in document ready function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.