I have some jQuery code where +$(...)
is used in many places. The code does not work without the +
part, when doing just $(...)
.
I couldn't find any explanation through Google. I'd appreciate any guidance if possible.
function calculate() {
var a = +$('#a').val(); // what is +$ ?
var b = +$('#b').val();
var c = b * 108.40;
//etc
}
In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.
jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.
This is a shortcut for $(document). ready() , which is executed when the browser has finished loading the page (meaning here, "when the DOM is available").
In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $ . If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.
+$()
is actually two operations, where first $()
runs to grab your input and then +
coerces whatever the value of the input is into a number.
Here's a breakdown of what is happening:
var valueA = $('#a').val(); // "123"
var numberA = +valueA; // 123
console.log('valueA is a ' + typeof valueA); // 'valueA is a string'
console.log('numberA is a ' + typeof numberA); // 'numberA is a number'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" value="123"/>
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