user1429496
user1429496

Reputation: 313

jQuery: How to hide div based on number value?

I'm trying to hide a div when a page loads, if the number within the span is 0.

Here's what I tried using, which did not work:

$(document).ready(function() {

   var x = $("span#number").val();

   if (x = 0){
     $("div#container").hide();
   };    

});​

Here's the fiddle I set up: http://jsfiddle.net/Cmsvj/

How do I make this work?

Upvotes: 1

Views: 1417

Answers (2)

Ram
Ram

Reputation: 144689

For span elements you should use text() method instead of the val(), also in the if statement change the = operator with ==, currently instead of comparing the value you are assigning the value:

$(document).ready(function() {
   var x = $("span#number").text();
   if (x == 0){
     $("div#container").hide();
   };        
});​

DEMO

Upvotes: 4

pimvdb
pimvdb

Reputation: 154858

http://jsfiddle.net/Cmsvj/1/

$(document).ready(function() {
   var x = $("span#number").text();

   if (+x === 0){
     $("div#container").hide();
   };
});
  1. Use .text instead of .val - a <span> is not an input element.
  2. Use === for equality; = is for assignment.
  3. Use + to convert to a number (.val returns a string).
  4. Select jQuery in the jsFiddle.

Upvotes: 1

Related Questions