Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery val() vs this.value for dropdowns

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);                 
    });
like image 652
danielb Avatar asked Oct 11 '12 07:10

danielb


People also ask

What is the difference between Val and value?

attr('value') returns the value that was before editing input field. And . val() returns the current value.

What does VAL () do in jQuery?

jQuery val() Method The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

Can jQuery Val return null?

val() returns an array containing the value of each selected option. As of jQuery 3.0, if no options are selected, it returns an empty array; prior to jQuery 3.0, it returns null .


1 Answers

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

like image 74
billyonecan Avatar answered Sep 20 '22 09:09

billyonecan