1

In coffee script I'm trying to figure out if something is included in an array or not. But can't seem to figure out the correct syntax. Is there not a way to do this without have to iterate over them?

Thanks,

  if $(this).val() is in ["needs_cover","comatose"]
    $("#head_count").hide()
  else
    $("#head_count").show()
2
  • 1
    $(this).val() in ["needs_cover", "comatose"] should work. Commented Sep 12, 2013 at 8:10
  • 1
    I knew I was close thanks! Commented Sep 12, 2013 at 8:13

2 Answers 2

6

Just drop the is:

if $(this).val() in ["needs_cover","comatose"]
    $("#head_count").hide()
  else
    $("#head_count").show()

That would translate to the following JavaScript:

var _ref;

if ((_ref = $(this).val()) === "needs_cover" || _ref === "comatose") {
  $("#head_count").hide();
} else {
  $("#head_count").show();
}
Sign up to request clarification or add additional context in comments.

Comments

0

If this is a common use case, you could write a function, which would also allow you to write a routine that is a bit more compact as well, like so:

hideShowFn = (valSelector, hideShowElSelector, compareArr) ->
    if $(valSelector).val() in compareArr then return $(hideShowElSelector).hide()
    $(hideShowElSelector).show()

I prefer doing the above as it flattens the code a little bit. This is my preference.

You would call the function like so:

hideShowFn this, '#head_count', ['needs_cover', 'comatose']

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.