开发者

What is wrong with this JS if Condition test?

this code works fine without the if condition test, where am I going wrong here with the if condition?

$(document).ready(function() {
  if ($("input[name=contest_open]").val() == true) {
  var refreshId = setInterval(function()
  {
       $('#tweets').fadeOut("slow").fadeIn("slow");
       $.get("/event", { event:$("input[name=event]").val(), }, function(data) {
         开发者_C百科console.log(data.success);
         console.log(data.page_link);
         console.log('Succesfully Loaded Data from JSON FORMAT GET');
         $('#tweets').html(data.html);
         $('#pagelink').html(data.page_link);
       });      
  }, 30000); 
  }
})


The problem is that val does not return a boolean value. If you are trying to check whether the value of input[name=contest_open] is not empty, try val() !== "" instead.

If you are trying to check whether the value is the string "true", you need to enclose true with quotes.


val() will return a string.

Use this if you want to test against "true"

$(document).ready(function() {
  if ($("input[name=contest_open]").val() === "true") {
  var refreshId = setInterval(function()
  {
       $('#tweets').fadeOut("slow").fadeIn("slow");
       $.get("/event", { event:$("input[name=event]").val(), }, function(data) {
         console.log(data.success);
         console.log(data.page_link);
         console.log('Succesfully Loaded Data from JSON FORMAT GET');
         $('#tweets').html(data.html);
         $('#pagelink').html(data.page_link);
       });      
  }, 30000); 
  }
})


If you want to check for existense, then use :

if ($("input[name=contest_open]").val()) 

only.

On the ither hand, if you intend to check the contents reading "true", you can use

if ($("input[name=contest_open]").val() == "true")

For the simple reason that val() function returns a string.


Well, since you have ==, 1 or an object will also evaluate as true. With === it will only evaluate as true if it is a boolean true.


Try this. If you think the value can contain "True" then its better to convert to lowercase.

$(document).ready(function() {
  if ($("input[name=contest_open]").val() == "true") {
  var refreshId = setInterval(function()
  {
       $('#tweets').fadeOut("slow").fadeIn("slow");
       $.get("/event", { event:$("input[name=event]").val(), }, function(data) {
         console.log(data.success);
         console.log(data.page_link);
         console.log('Succesfully Loaded Data from JSON FORMAT GET');
         $('#tweets').html(data.html);
         $('#pagelink').html(data.page_link);
       });      
  }, 30000); 
  }
})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜