Timo Timo - 20 days ago 5
CoffeeScript Question

jQuery: Each Loop Oddity

I want to go through all fields of a form and determine if the fields are populated with data. When all fields are given, I'd like a button

save
to appear.

This is the Fiddle with code, that works (!) ...



This is the same in JavaScript.



The jQuery-Object to iterate through:

formElements = $ 'form input[type="text"], form input[type="number"], form textarea'


The Function:

formFilled = ->
filled = true
formElements.each ->
if $(this).val().length is 0
filled = false
filled


The Event-Handler:

formElements.on 'keyup', (keyup) ->
keyup.preventDefault()
if formFilled()
save.show()
else
save.hide()


Any suggestions?

Answer

# I know the answer:

JavaScript validates the number-input fields and accepts only values that are numbers.

I stupidly tested those fields with text input ... silly.

The code is fine. Just the testing was bad. Sorry for wasting your time.

This works:

formInputs = $ 'input[type="text"], input[type="number"], textarea'

formFilled = ->
  filled = true
  formInputs.each ->
    if $(this).val().length is 0
      filled = false
  filled

formInputs.on 'keyup', (keyup) ->
  if formFilled()
    saveButton.show()
  else
    saveButton.hide()