Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+$ in jquery. How come not only the basic $

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
}
like image 965
Mik_A Avatar asked Nov 04 '16 19:11

Mik_A


People also ask

What does $$ mean in jQuery?

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.

How do I run a function only once in jQuery?

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.

What does $( function ()) shorthand do?

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").

Can you use any other name in place of in jQuery?

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 $.


1 Answers

+$() 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"/>
like image 50
nem035 Avatar answered Oct 22 '22 04:10

nem035