Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could check if</p> <pre><code>$('#inputId').length &gt; 0 </code></pre> <p>i.e. if the current selector matched any elements.</p> <p>But if <code>$('#inputId').length == 0</code> then <code>$('#inputId').val()</code> will be <code>undefined</code>. This is different from the scenario where the input exists, because <code>val()</code> would always yield a string, that is or isn't null.</p> <p>Now, you would produce an <em>error</em> only if you're trying to do stuff with the value, that may or may not be <code>undefined</code>. For instance, the following would not work if <code>#inputId</code> does not exist in the DOM:</p> <pre><code>if($('#inputId').val().length &gt; 0) { ... } </code></pre> <p>... since you'd be trying to access <code>undefined.length</code>. However, you could still do</p> <pre><code>if(!!$('#inputId').val()) { // this code will only be executed if #inputId exists, and has a value that // is not an empty string } </code></pre> <p>If you're writing form validation, it might be more useful to do</p> <pre><code>if($('#inputId').val() !== '') { // this code will be executed if #inputId has a value, or if it does not // exist in the DOM at all } </code></pre> <p>The former condition checks that the result of <code>.val()</code> resolves to true, which is not the case for an empty string or for undefined. (It is also not the case for <code>null</code>, <code>NaN</code>, <code>false</code> or <code>0</code>, but <code>.val()</code> will never yield any of those results)</p> <p>The latter checks that the result of <code>.val()</code> is not exactly an empty string, which is true for an actual value, as well as for <code>undefined</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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