30

I been searching but I can only find articles talking about one or the other. Which one is better?

I'm making a small web app where performance is not a big concern since there's nothing complex going on.

I considered using jQuery's val() function since maybe it solves some inconsistency I'm not aware of, but getElementById.value IS faster (although the end user won't notice.)

So which one should I use? Is jQuery's non-native method worth the lower performance to gain more compatibility?

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Juan Ignacio
  • 3,217
  • 8
  • 33
  • 53

7 Answers7

43

The biggest advantage of using jQuery().val() over document.getElementById().value is that the former will not throw an error if no elements are matched, where-as the latter will. document.getElementById() returns null if no elements are matched, where-as jQuery() returns an empty jQuery object, which still supports all methods (but val() will return undefined).

There is no inconsistency when using .value for form elements. However, jQuery.val() standardises the interface for collecting the selected value in select boxes; where as in standard HTML you have to resort to using .options[this.selectedIndex].value.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • 3
    Actually there is some inconsistency between browsers with line breaks in textarea `value`s that jQuery's `val()` normalizes, although I would rather it didn't. – Tim Down Sep 07 '11 at 00:12
  • 1
    @TimDown Do you have more info regarding the inconsistencies? On Chrome 53, Firefox 47 and Safari 9.1 on Mac OS X at least there aren't any. Tested with this fiddle: https://jsfiddle.net/5hvy75Lf/ – Dennis98 Sep 28 '16 at 20:00
  • 1
    @Dennis98: HTML5 has sorted this issue out because it has standardized on just using the LF character for any line break in the value and I think all recent browsers comply. Certainly old IE, and possibly some old versions of Safari and/or Opera, used CR+LF rather than just LF. – Tim Down Sep 29 '16 at 10:55
  • Ah, ok. Thanks! :) – Dennis98 Sep 29 '16 at 19:27
7

If you're using <select> elements as well, .value won't work whereas .val() will.

I would not mind about performance of just getting a value. If you want the best performance, perhaps you shouldn't use a library at all.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
3

jQuery does so many nice little error handling things (look below) that I would never write a line of javascript without jquery in a browser again.

  • First, val works on checkbox groups, selects, gets html, and the like.
  • Second, $ lets you use sizzle selectors, so in the future, you can easily switch between an ID and a CSS path.
  • Third, your code will be so much easier to read and maintain if you just use jQuery, that the time you save maintaining your code outweighs any speedup that you admit your users won't see. Finally, jQuery is a very popular, very widely used library. They will make $ and val as fast as they can.
David Souther
  • 8,125
  • 2
  • 36
  • 53
  • just a small note: val() does **not** (unfortunately) work on checkboxes, at least not in any useful way. It returns the value that would be set if the checkbox was checked - but it doesn't take into account whether if it is checked or not. +1 for not writing a line of JS without jQuery. – johndodo Dec 27 '11 at 06:51
1

I think using pure Javascript is quicker for the following reasons:

  1. You won't have to learn more than pure js
  2. If you don't want errors, use catch(exeption) (I think...)
  3. You don't have to put in that little extra time to type in the code to initiate jquery
  4. The browser responds quicker if you don't use jquery
  5. Normal js works (in a better way) on checkboxes @johndodo

Thank you for listening to my answer.

0

I've been looking into the performance differences with this recently and, slightly unsurprisingly, using vanilla JS to grab a value is faster than using jQuery. However, the fallbacks that jQuery provides to prevent errors, like what @Matt mentioned, is very useful. Therefore, I tend to opt for the best of both worlds.

var $this = $(this),
    $val = this.value || $this.val();

With that conditional statement, if this.value tries to throw an error, the code falls back to the jQuery .val() method.

Joseph Shambrook
  • 320
  • 6
  • 14
0

Here https://www.dyn-web.com/tutorials/forms/checkbox/same-name-group.php is an implementation for checkboxes, apparently options just need to be named the same with the array brackets notation in the name i.e.: name="sport[]" then yu get the array inJavascript via: var sports = document.forms['demoForm'].elements['sport[]']

I was looking for a selection type field solution without using jQuery and I came across this solution:

The Selection group is an object: HTMLCollection, and it has a lenght method and a selectedOptions property, which allows you to iterate through its label properties to populate an Array with the selected options, which then you can use:

...
    vehicleCol = document.getElementById('vehiculo').selectedOptions;
    vehiculos  = [];

    if (vehicleCol !== undefined) {
        for (let i = 0; i < vehicleCol.length; i++) {
            vehiculos.push(vehicleCol[i].label.toLowerCase())
        }
    }
...

Web app and Console

-3

I'd use jQuery's val(). Shorter code means faster download time (in my opinion).

Obi
  • 49
  • 4
  • 7
    If you're using jQuery, yes. Otherwise I doubt the savings from `document.getElementById('test')` to `$('#test')` weigh up the 31KB of the library itself. – pimvdb Sep 06 '11 at 15:19
  • 1
    When we talk about using jQuery I assume the library is already loaded for other reasons, I don't anybody would load jQuery just to get field values. – Juan Ignacio Sep 08 '11 at 17:46