TheFron
TheFron

Reputation: 15

If else statement with else part not working

I am writing a if/else statement that includes css in it. The if part works but the else part does not. What am I doing wrong, can someone guide me thanks?!

This is my statement.


if(!$(#ron.val()){
   $("#ron_lan").attr("disabled",true).css({"opacity":0.3});
}
else{
   alert('else');
   $("select#ron_lan").attr("disabled",false).css({"opacity":1});    
}

Upvotes: 0

Views: 119

Answers (2)

Juank
Juank

Reputation: 6196

Depends on what the value of #ron is. If it is an input the possible values are text, empty or spaces.

For example:

!""             // Negating an empty string gives you TRUE
!" "            // Negating a space gievs you FALSE
!"any text 123" // Negating any text gives you FALSE
!undefined      // Negating undefined gives you TRUE, read on...

It can also depend on the existance of #ron. If the element with id #ron does not exist, or does not have a "value" property (is not an input). jQuery will always return undefined which could explain why !undefined will always return true and your else path is never reached.

Recap:

  1. Check if #ron exists on the html eg. $('#ron').length should return 1
  2. Check that #ron is an input or textarea so that $('#ron').val() wont return undefined
  3. Check the values in the textarea and trim it to avoid spaces vs empty string scenarios

Upvotes: 1

Cjmarkham
Cjmarkham

Reputation: 9681

$(#ron.val() is invalid and will always be false. It should be

$('#ron').val()

Notice the brackets and quotes. #ron is the selector in this case.

Also, don't use attr('disabled', false). You should just remove the attribute entirely with removeAttr('disabled')

Upvotes: 5

Related Questions