Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else in coffee script

Folks,

I have two text boxes in my html. I wanted to compare their values using coffee script. Although I have googled about it, and I am kind of sure that I am doing what is expected to do but still I see a strange behavior.

Thing is :

Lets say, I have two text boxes with id as "title" and "author". Along with that, I have a button which onclick triggers the coffee script function.

My coffee script function looks as:

check_fields = ->
  elem_book_title  = $("#title").val()
  elem_book_author = $("#author").val()
  alert(elem_book_title)
  alert(elem_book_author)
  if not elem_book_title? 
    alert("title is null")
  else if not elem_book_author?
    alert("author is null")
  else
    alert("both are ok")

Situation is, If I enter something only in my "title" textbox, it should alert me that "author is null". Right? But surprisingly, it alerts me that "both are ok".. Expected? Or I missed something?

like image 742
Rahul Bhargava Avatar asked Nov 15 '25 12:11

Rahul Bhargava


1 Answers

In jQuery, .val() won't return null for an empty field (except for a select element). Right now your coffee script evaluates to:

if (elem_book_title == null) {
  return alert("title is null");
} else if (elem_book_author == null) {
  return alert("author is null");
} else {
  return alert("both are ok");
}

So try removing the question marks

if not elem_book_title
  alert("title is null")
else if not elem_book_author
  alert("author is null")
else
  alert("both are ok")

This will produce the js I think you were expecting (which is testing for falsiness like an empty string, 0 or null):

if (!elem_book_title) {
  return alert("title is null");
} else if (!elem_book_author) {
  return alert("author is null");
} else {
  return alert("both are ok");
}

There is a question about the way coffeescript's existential operator (?) works here that you may find informative (thanks @raina77ow).

like image 110
jcuenod Avatar answered Nov 17 '25 07:11

jcuenod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!