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
}
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
}
Share
Improve this question
edited Nov 4, 2016 at 19:26
nem035
35.5k6 gold badges92 silver badges104 bronze badges
asked Nov 4, 2016 at 19:02
Mik_AMik_A
3665 silver badges16 bronze badges
3
- It's the other way around , var a += $('#idofinput').val(); – DinoMyte Commented Nov 4, 2016 at 19:03
- Well it is not in the code I have. It is like I said. Or maybe you mean it should be the other way around? – Mik_A Commented Nov 4, 2016 at 19:06
-
3
var a += ...
is a syntax error. – JJJ Commented Nov 4, 2016 at 19:09
1 Answer
Reset to default 11+$()
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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" value="123"/>