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);
});
attr('value') returns the value that was before editing input field. And . val() returns the current value.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With