Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As long as your selector is actually working, I see nothing wrong with your code that checks the length of the array. That should do what you want. There are a lot of ways to clean up your code to be simpler and more readable. Here's a cleaned up version with notes about what I cleaned up.</p> <pre><code>var album_text = []; $("input[name='album_text[]']").each(function() { var value = $(this).val(); if (value) { album_text.push(value); } }); if (album_text.length === 0) { $('#error_message').html("Error"); } else { //send data } </code></pre> <p>Some notes on what you were doing and what I changed. </p> <ol> <li><code>$(this)</code> is always a valid jQuery object so there's no reason to ever check <code>if ($(this))</code>. It may not have any DOM objects inside it, but you can check that with <code>$(this).length</code> if you need to, but that is not necessary here because the <code>.each()</code> loop wouldn't run if there were no items so <code>$(this)</code> inside your <code>.each()</code> loop will always be something.</li> <li>It's inefficient to use $(this) multiple times in the same function. Much better to get it once into a local variable and then use it from that local variable.</li> <li>It's recommended to initialize arrays with <code>[]</code> rather than <code>new Array()</code>.</li> <li><code>if (value)</code> when value is expected to be a string will both protect from <code>value == null</code>, <code>value == undefined</code> and <code>value == ""</code> so you don't have to do <code>if (value &amp;&amp; (value != ""))</code>. You can just do: <code>if (value)</code> to check for all three empty conditions.</li> <li><code>if (album_text.length === 0)</code> will tell you if the array is empty as long as it is a valid, initialized array (which it is here).</li> </ol> <p>What are you trying to do with this selector <code>$("input[name='album_text[]']")</code>?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload