1

Is it possible without jQuery and using CoffeeScript to create a 1 liner that lets me know if there are any inputs without a value?

This checks for it but I would like to improve on it if possible

any_blank_fields = false
for field in $('form input[type="text"]')
  any_blank_fields = true if field.value == ''
John Pollard
  • 3,729
  • 3
  • 24
  • 50

1 Answers1

1

1. Coffeescript one liner

It's possible, but I don't think it's the cleanest or nicest solution:

any_blank_fields = '' in (field.value for field in $('form input[type="text"]'))

The in operator checks if the value on the left exists in the array on the right. The loop inside the parenthesis maps the array of jQuery objects into an array of the fields' values.


2. jQuery filter

There are some jQuery specific solutions which may work better, such as using filter (see this question). Here is the CoffeeScript version:

emptyFields = $('form input[type="text"]').filter -> this.value is ''

This returns an array of all empty fields, you could convert this to a boolean using

!!emptyFields.length # as zero values are falsey

3. CSS Selector

If all of your input elements have value properties in the HTML, you can use:

anyEmptyFields = $('form input[type="text"][value=""]').length > 0 
Community
  • 1
  • 1
caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40
  • Your 1st answer is what I was looking for thanks! One question, whenever I run #3, it never works. That has been part of my frustration. If I type "asd" into a blank input field and then go to the console and type "$('form input[type="text"][value=""]').first().val()" 'it yeilds "asd"... Shouldnt it be blank? – John Pollard Mar 27 '17 at 14:28
  • @JohnPollard Interesting, it worked for me in Chrome 57. Could you create a JS fiddle of this problem? And please let me know what browsers you are using – caffeinated.tech Mar 28 '17 at 10:09