Mark Locklear
Mark Locklear

Reputation: 5335

coffeescript or operator on bind "change"

My exsisting code looks like this...

jQuery ->
  to_date = null
  from_date = null
  $("#to_date").bind "change", ->
    from_date = new Date($('#from_date').val())
    to_date = new Date($('#to_date').val())
    if from_date > to_date
      $("#date_error").text("Error! Not a valid date range")
    else
      $("#date_error").text("")
  $("#from_date").bind "change", ->
    from_date = new Date($('#from_date').val())
    to_date = new Date($('#to_date').val())
    if from_date > to_date
      $("#date_error").text("Error! Not a valid date range")
    else
      $("#date_error").text("")

...and works great. Essentially I am looking for a change on either the from_date or to_date input boxes. I'd like to use an or operator and get rid of the duplicate code. Some like...

$("#to_date").bind "change" || $("#from_date").bind "change", ->
    from_date = new Date($('#from_date').val())
    to_date = new Date($('#to_date').val())
    if from_date > to_date
      $("#date_error").text("Error! Not a valid date range")
    else
      $("#date_error").text("")

Thanx in advance!

Upvotes: 0

Views: 369

Answers (1)

shakib
shakib

Reputation: 5469

Use jquery's multiple selector to combine the selection and bind the change event on them as,

$("#to_date, #from_date").bind "change" , ->

relevant doc Multiple Selector

Regards

Upvotes: 1

Related Questions