Well, I'm a bit confused about how to obtain the value of the fields in Javascript, I have seen that many times it is obtained using the code:
document.getElementById("elemento").value;
and others using the code:
$(elemento).val()
what is the difference?
They are two ways of doing the same thing.
$ is the variable name that refers to the document object in jQuery, a very popular JavaScript library . The official jQuery documentation is at https://jquery.com/
document is a native variable that references the document object.
The document object has the purpose of managing in memory the content of the web page loaded in the browser. What governs its characteristics is known as the Document Object Model, or DOM. It is not part of the ECMAScript specification, which is the standard for specifying how JavaScript engines should handle scripts made with this language, but rather has its own standard published by the W3C.
The ECMAScript web address is http://ecma-international.org/ecma-262/
The web address for the DOM is https://www.w3.org/DOM/
jQuery was born when JavaScript lacked easy ways to do operations with the DOM however over the years it has improved as well as jQuery has, however other libraries and frameworks have emerged that offer similar things. Frameworks are tools that can help a programmer to be more efficient, but like any tool, the right one for the task must be chosen.
Related
Should jQuery be used in "every" HTML/CSS/JavaScript application?
The difference is that the code without jQuery is one line, while with jQuery it 's many lines, and it's a gimmicky code that tries to work in all browsers.
Without jQuery :
To get the function code
val
in jQuery , do the following, using the uncompressed version of jQuery called slim , in its download section :The response I got was the following:
when you use
$
these referring to JQuery which is a JavaScript library, its main use is as a selector, which is the example you give, but it has many more uses, such as animations, simpler ajax requests and much more. For more information visit the main page . When you usedocument.getElementById("elemento")
these using the native javascript way to reference an element by id. In JQuery it is:They do the same thing, as Reinier says $ refers to Jquery while GetElementById is the native Javascript method.
I remind you that Jquery is written in Javascript, so bringing the value of both forms is valid.
As everyone has expressed,
.val()
and.value
it's the same but I wanted to add something.The reason you use
.val()
about.value
is to make sure it works in all browsers. For example.innerHtml
, it did not work the same in all browsers but jquery solved it for us with.html()
, doing all the dirty work of making it work according to the browser and thus giving a single method for all browsers (desktop and smartphone). It gives us easy API to manipulate the DOM.