jQuery: Check For Non-Empty Input Fields

Posted in Code

– Check out some of our more recent Ruby on Rails blog posts. If you’d like to hire our team, get in touch

I was writing some code today and I wanted to prompt the user to check if they wanted to delete a row of data only if there was some data they might not want deleted. Typically to do this I would loop through all the input fields and if any of them weren’t blank I would run the check. I figured that there must be a better way with callbacks or selectors, and after a little thinking I wrote this jQuery snippet :

row.find('input[value!=""]').length > 0

This basically says count the number of inputs with a non-blank value you find, inside the given row.

Just like my last post, it’s nothing amazing but it sure is a better way of doing things. If you look into the andSelf() method then you could also easily chain selects and other input types.

I’m also interested if someone has a better way to approach this problem?

5 Comments

  • Tony

    Nov 19, 2008

    Cool idea.

  • Marko

    May 28, 2009

    doesn’t work
    in debugger I can see that length is always 1
    it works if I write code like this:

    row.find(‘input[value!=""]‘).val().length > 0

    cheers

  • Aaron

    May 29, 2009

    I’m not sure what to say, my code does work and I’ve tested it in application and also again just now in Firebug. I’d check your HTML for hidden fields, or just do a bit of debugging to find the field that is being reported back to give you a length of 1.

    Your code is actually incorrect as a solution to the problem I was trying to solve here. You’re chaining a single element function against a function that returns an array. In jQuery issuing the val() function against an array of elements will issue the val() function against the first element. In this case it will be an input element that is non-blank, and so your length will always be > 0, as you’re just getting the length of the string.

    In my example I am trying to check if there are any elements that contain some data, so I’m trying to find the length of the array of input elements that aren’t blank.

    Let me know if you have any further questions.

    Cheers :)

  • anirudha

    Sep 11, 2009

    how this function works

  • anirudha

    Sep 11, 2009

    please write a blg blog

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Twitter

Great web stats at @petrescue , the driving force behind the rebuild of their systems by @frontiergroup . http://t.co/MTvfoxnU

@frontiergroup about 2 weeks ago #

Search Posts

Featured Posts

Categories

Archives

View more archives