5

The below code uses this.value to get the value of a forms dropdowns. I have only generally seen .val() used. Is the below way acceptable cross-browser (especially older verions of IE)? Thanks!

    $(':input', '#all').each(function() {
       alert(this.value);                 
    });
danielb
  • 878
  • 4
  • 10
  • 26

2 Answers2

6

Yes, it's acceptable, is more readable, and is less expensive (faster) than calling $(this).val().

Simply put, $(this) refers to a jQuery object, whilst this refers to a DOM element.

The FAQ here touches upon it briefly (under 'Know Your DOM Properties and Functions')

You should use plain "this" when the native DOM APIs suffice, and $(this) when you need the help of jQuery.

I'd also suggest reading the following:

$(this) vs this in jQuery

jQuery: What's the difference between '$(this)' and 'this'?

When to use Vanilla JavaScript vs. jQuery?

utilizing-the-awesome-power-of-jquery-to-access-properties-of-an-element

this demystified

Community
  • 1
  • 1
billyonecan
  • 20,090
  • 8
  • 42
  • 64
-1

This should work

For JQuery val you need $(this).val()

NSF
  • 2,499
  • 6
  • 31
  • 55