Hey guys. I don't know much JS, but I wanted to do some quick work with jQuery.
But I've been staring at this for about an hour and I don't understand what I missed:
<script type="text/javascript">
$('#qty_6035').change(function () {
var substractedQty, stockQty, remQty;
substractedQty = (int) $('#qty_6035').val(); // missing ; before statement
stockQty = (int) $('#orig_qty_6035').val();
$('#rem_qty_6035').html(stockQty-substractedQty);
});
</script>
jQuery library is included at the beggining of the document.
Thanks.
Use parseInt function, not (int) casting
Javascript is a dynamic language so in order to convert a string into a number you could use the parseFloat/parseInt functions:
<script type="text/javascript">
$('#qty_6035').change(function () {
var substractedQty = parseFloat($('#qty_6035').val());
var stockQty = parseFloat($('#orig_qty_6035').val());
$('#rem_qty_6035').html(stockQty - substractedQty);
});
</script>
JavaScript is not Java. int is a reserved keyword but doesn't have any functionality assigned to it, and you can't cast a value that way.
You probably want:
substractedQty = parseInt($('#qty_6035').val(), 10);
Javascript doesn't support type casting like strong typed languages (C#, Java) do. To convert the field values (which are strings) to numbers you need to use the global functions parseInt() or parseFloat().
You'll probably also want to make sure the values are parsed correctly, in case a user entered some bad input instead of a number. Use isNAN() for that.
Related
I got a variable Javascrpit which has a number as a string in this case 0.84. I'm trying to convert it into a float but when I try to it appears a 0 as float instead the 0.84.
I'm using this:
var pot="0.84";
var asd = parseFloat(pot);
console.log(asd);
EDIT:
This is not exactly the example. I recover data from the HTML and it works for other numbers but not for this. It is difficult to explain my problem exactly. It is a lot of code and works for other numbers so don't know exactly.
Your input is not "0.84". If you test with that, you will get the correct answer. Your input has something else inside, like spaces, for example:
"0 .84"
This should be the solution:
parseFloat(pod.replace(/ /g, ""))
I have tried this example on my end and it completely worked. However, you can try to instead input the string value directly into the parse float() function and it should print our your expected value. If you still want to assign the parsefloat() to a variable, then try to either rewrite the code or re-open your IDE because the code should work.
var pot = "0.84"
console.log(parseFloat(pot))
or you can just write it in one line
console.log(parseFloat("0.84"))
I am using the following
var loan = parseFloat(document.getElementById("loanamount"));
document.getElementById('numpay').textContent = loan.toString();
and my html is this:
<p>Number of Payments: <a id="numpay"> </a> </p>
I feel like this should be working but cannot seem to get anything other than NaN in my html, no matter how I configure it. I know I am a novice at javascript but could you please give me a tip?
Thanks!
You need parseFloat(document.getElementById("loanamount").value) most probably
TIP: Instead of parseFloat, just use + to convert from strings to numbers. So +document.getElementById("loanamount").value should also serve your purpose.
var loan = parseFloat(document.getElementById("loanamount").value);
document.getElementById('numpay').textContent = loan.toString();
If you aren't doing anything with loan then just do this:
document.getElementById('numpay').textContent = document.getElementById("loanamount").value
If the element with id loanamount is an input you will need .getElementById("loanamount").value, if it is a span or div then .getElementById("loanamount").innerHTML. For writing back the same apply.
But in either case you must not use .toString() on the write in. parseFloat() will give you a number, which does not have methods. JavaScript is not that similar to Java.
var loan = parseFloat(document.getElementById("loanamount").value);
document.getElementById('numpay').innerHTML = loan.toFixed(2);
As JavaScript uses floating point maths for all numbers, which does not preserve precision in all cases, I want to parse a JSON object containing numbers but generate strings in the returned JavaScript object rather than number objects. Is there a way to do this using standard or third party libraries?
You can do something like this. This may not be a perfect solution (especially the reg expression), but hope it will help you to solve this.
var json = '{"num1":123.89075576575775676575, "num2":89.5564764646476444844, "num3":56.4353454354353535435435435}';
json = json.replace(/\d+.\d+/g, function(a, b){
return '\"' + a + '\"';
});
console.log($.parseJSON(json )); // I have used jQuery. Any JSON parser can be used
You can try a regexp, something like:
var numstrings = JSON.parse(json.replace(/\:([0-9.]+)(,?)/g,':\"$1\"$2'));
http://jsfiddle.net/rmwcZ/
I am using ASP.Net MVC 3 Razor view engine.
I have a requirement to generate some JavaScript code in my View based on a value in my View Model. The value I need to use is a boolean, for this example lets call it IsSet.
So what I want to do is create a JavaScript boolean based on this value that I can use in the script later on.
Keep in mind that for all below examples I have this bit of code at the top of my view...
#{ string IsSet = Model.IsSet ? "true" : "false"; }
NOTE: All examples below are JavaScript.
First attempt...
var IsSet = #(IsSet);
... this actually works, the problem is it breaks the auto-formatting (CTRL + E, D) in VS 2010 due to badly formatted JavaScript - as you might expect, and this is not acceptable.
Second attempt...
var IsSet = "#(IsSet)";
...I know, JavaScript is clever, it will auto-parse my string when needed. Ooops, forgot it is a string type and anything other than empty evaluates to true.
Third attempt...
var IsSet = Boolean("#(IsSet)");
....surely this will work... nope, convert non-empty string to true again (bad parser!)
Fourth attempt...
var IsSet = "#(IsSet)" === "true";
Finally something that works, but it doesn't look great to me.
I will use this if need be but ultimately my question is: Is there a better way to handle this kind of situation? Perhaps, the unwanted behaviour in my first attempt is just something that Microsoft may have overlooked?
If anybody has a nice and tidy fifth attempt for me, that would be good.
The important thing for me is that the auto-formatting in VS 2010 does not break
Thanks
I just wrestled with the same issue for about an hour. My final solution was equivalent to the following.
var IsSet = #(Model.IsSet.ToString().ToLower()); // Inside JavaScript block
This requires no additional code.
None of the versions shown so far (both in the question and answers) is something that I would use. Here's how I would do it:
#model MyViewModel
<script type="text/javascript">
var isSet = #Html.Raw(Json.Encode(Model.IsSet));
// TODO: use the isSet javascript variable here as a standard boolean value
</script>
or if you needed other properties of your view model to be manipulated with javascript you could JSON encode the entire model:
#model MyViewModel
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
if (model.IsSet) {
alert(model.FooBar);
}
</script>
Version 1 is the only one of those that I'd vote for even if they all worked, because it's the most human-readable. Unfortunately I don't have VS at home so I can't try it out to see what the auto-formatting issue is, but if at all possible I'd want to ignore the issue and go ahead and use that version given that there's nothing actually wrong with the code - it is just VS that is confused. (Are you saying VS is trying to interpret the whole thing as JS and thus finding it invalid?)
But if you want some other options:
Fifth attempt...
#{ string IsSet = Model.IsSet ? "true" : ""; }
var isSet = !!"#(IsSet)";
// OR
var isSet = Boolean("#(IsSet)");
Coerce the string value into a boolean with the old double-not-operator trick - as you already pointed out both "true" and "false" would become true, but this problem goes away if you use "true" and "" (empty string) - so you can use Boolean() as per your "third attempt".
Sixth attempt...
#{ string IsSet = Model.IsSet ? "true" : "false"; }
// helper function at the top of your page:
function bool(strVal) {
return strVal === "true";
}
// variable declaration
var isSet = bool("#(IsSet)");
OK, so you end up with a fairly pointless function at the top of your page, but it keeps the actual variable declarations reasonably tidy and if debugging client side you'll see bool("false") or bool("true").
Seventh attempt...
I don't like the extra step of creating the server-side string IsSet = Model.IsSet ? "true" : "false"; in advance. I don't know Razor syntax, but can you say something along the lines of:
var isSet = !!"#(Model.IsSet ? "true" : "")";
// OR, better:
var isSet = !!"#(rzrBool(Model.IsSet))";
// where rzrBool() is a server-side helper function (that you would create)
// which returns "true" or ""
I would expect all of my "attempts" to work, but again I think your "first attempt" is the best option.
How about:
#Ajax.ToJson(Model.IsSet)
var isSet = /true/i.test('#Model.IsSet');
Single line
Handles the case difference between .Net and JavaScript
Works with auto-formatting (Visual Studio, and Visual Studio with Resharper)
Reasonably idiomatic if you are familiar with JavaScript regexes
Fairly resilient to logic errors; it should do as intended or throw a JavaScript error (or possibly a Razor compilation error).
How about:
#Model.IsSet.ToString().ToLower()
var isSet= #((bool)Model.IsSet?"true":"false");
Here is what I use, inside a javascript block:
var someValue;
#{ var someValue= "someValue= " + Model.SomeValue+ ";"; }
#someValue
I know this is an old question, but none of the answers are particularly elegant.
The simplest solution in these situations is simply to append +0 to your conditional. This implicitly converts the bool to an int, but since the result is 0 or 1 it's immediately converted back again by the if statement. Example:
// The space is optional
if (#IsSet +0) {
// Do stuff
}
Assigning a boolean value to a variable could be achieved as follows:
// Note the double (not triple) equals, which performs type conversion
var isSet = #IsSet+0 == true;
The code works, you get no red squiggly lines, and the Visual Studio formatter is happy.
What I'm attempting to do can be accomplished by the following...
elementContent = document.getElementById('docElement').innerHTML;
elementContent = parseFloat(elementContent);
or even by...
elementContent = parseFloat( document.getElementById('docElement').innerHTML );
but I can't help to wonder if there's a more elegant way to retrieve and assign DOM content as a float that I may be unaware of. Any insight?
There is the unary plus operator which tries to convert a string (or another type's toString()) to a number. It would be used like:
elementContent = +document.getElementById('docElement').innerHTML;
As others have mentioned you can use jQuery as essentially syntactic sugar for .innerHTML here, also.
That's a fine way to go about doing things. The only thing I could suggest would be that if you can avoid working with the HTML markup entirely, by storing the "clean" number as an attribute of the element, that would be preferable, as it would get around problems that might be introduced if the HTML gets fancier than you expect it to be. (For example, sometimes designers want negative numbers formatted with the Unicode "minus" glyph instead of the plain hyphen, because it looks better.)
Thus if you could generate your elements like this:
<span id='docElement' data-value='29.20221'>29.20221</span>
then instead of accessing the value as ".innerHTML" you'd use ".getAttribute()":
var value = document.getElementById('docElement').getAttribute('data-value');
value = parseFloat(value);
Use JQuery:
var html = parseFloat($('#docElement').html());
$('#docElement').html(html);
If you use a library such as jQuery the code for this would be more elegant, like so:
var el = parseFloat( $('#docElement').text() );
Don't forget you might run into an issue where you need to trim() the string as well.