I have an AJAX call which gets time (in minutes) from a database. However, if the value fetched from the database is null, I want to replace "null" to show "0 minutes". Right now, it doesn't display anything if the time is null.
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$(function() {
$.getJSON($SCRIPT_ROOT + '/_ajax',
function(data) {
$("#timePeriod").text(data.timePeriod);
if (data.timePeriod == null) {
data.timePeriod = '0';
}
});
});
This is then displayed in the HTML using the following span tag:
Average time: <span id="timePeriod"></span> mins
The if statement in my AJAX code doesn't work as intended. It doesn't display anything (not even null, although that is what's being returned). How can I properly replace this value so that it displays a '0' when the result is null?
If I understood the problem properly (despite I'm not really aware why you are using data.wait), it should be as easy as:
data.timePeriod = !isNaN(+data.timePeriod) ? +data.timePeriod : '0';
$("#timePeriod").text(data.timePeriod);
Explanation:
(Logically) you want to check whether the data you are receiving is valid. It may be null (sure), but it also may hold any other strange value. So, to be 100% sure that the value actually can be parsed, we firstly try to cast it to a number (using the unary operator +), then we check whether it's NOT a NaN: !isNan, the evaluation will return true if the the result effectively is a number.
If it is, it assigns the value to the data object, else it assigns '0'.
The second line just put the value in the span element.
document.getElementById('timePeriod').innerText = +data.timePeriod
Using + converts to a number, +null is already 0.
document.getElementById('timePeriod').innerText = +null
Average time: <span id="timePeriod"></span> mins
Related
I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());
It's really weird.
$(function(){
$('.dial').knob({
return value + '%';
});
});
That was my original code to get the percent sign to show up, which works great. For some reason, when the value is 0, on page load it displays as NaN. The weird thing is that only once you highlight the text and then click off does it show the actual value of 0 (replacing the NaN value). Any idea what is causing this to happen? I tried to handle it in the format hook:
$(function(){
$('.dial').knob({
'format': function( value ){
if(value == undefined || value == NaN {
value = 0;
return value + '%';
}
else{
return value + '%';
}
}
});
});
It still doesn't work. I console logged the value I'm passing in, and sure enough it is 0. I'm thinking it may be an 'x loads before y' and therefore it sees the value as undefined, since I am passing in the value attribute by an angularJS data binding. But I'm trying to handle it to no avail. Any thought's on this?
value == NaN will not work because, surprisingly, in javascript NaN does not equal NaN. try isNaN() instead.
I've got the following variables in my simple javascript calculator:
var distance = parseInt(document.getElementsByName("distance"), 10);
var mins_running = parseInt(document.getElementsByName("mins_running").value, 10); // the running pace minutes
var secs_running = parseInt(document.getElementsByName("secs_running").value, 10); // the running pace seconds
var mins_walking = parseInt(document.getElementsByName("mins_walking").value, 10); // the walking pace minutes
var secs_walking = parseInt(document.getElementsByName("secs_walking").value, 10); // the walking pace seconds
The problem is, when I try to use these variables (entered as text from a form but meant to be used as numbers in the calculator). When I do a typeof() in the developer console.log I'm told the values are of type 'number', but the very next line is also a console.log('mins_running'), for example, and it explicitly states the value is "NaN". Is my value a number or not? What's going on? Stupid javascript--be more normal, darn it!
Any reasonable input/help will be appreciated.
Thanks for all the help, guys. Looks like I'm back to using the old Form.elementName.value thing instead. (if this is a really bad idea or just not good for production code at all, please feel free to say something.)
document.getElementsByName("mins_running")
returns a NodeList, which has no attribute value. Use
document.getElementsByName("mins_running")[0].value
instead.
Example:
HTML:
<input type="text" name="mins_running" value="10">
<br><button id="theButton">Click Me</button>
JavaScript:
document.getElementById("theButton").onclick = function() {
// Note we're getting the first match ----------------vvv
var field = document.getElementsByName("mins_running")[0];
display("The field's current value is: " +
parseInt(field.value, 10));
// And using its value-^^^^^
};
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Live Copy | Source
Waleed shared how to fix it.
The technical reason why you got NaN there is...
You grab a reference to a NodeList with document.getElementsByName("distance"), and you attempt to access the property value on that. That property does not exist on NodeList, or anywhere on the prototype chain. In JavaScript, that means undefined is returned.
When you call parseInt() with undefined as the first argument, the function will toString() it and return "undefined". You explicitly set the base as 10, which obviously only covers digits 0 to 9, and the number can't be parsed. When this happens, parseInt() returns NaN. Since NaN is of the Number type (it's part of the IEEE-754 specification), the typeof operator tells you it's a "Number".
If you'd set the base as 31, it'd be able to parse "undefined", and it'd be 26231474015353 :)
Set ids for your tags and use getElementById instead.
I've got an two if() statements, for which the conditions are both met with the default values in the <select> and <input> form fields I've tested this by assigning the values to a variable and writing the variable. (0 and Url).
However, it seems that neither if() statement's contents execute properly.
Here's a link to my JSFiddle: http://jsfiddle.net/cfRAk/2/
Any edits/answers as to why this is happening would be greatly appreciated!
Change this line:
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
To this:
var geo_select_val = parseInt($('select[name=g_country\\[1\\]]').val());
The thing is geo_select_val is actually "0" and not 0. Converting a string to boolean will only result in false if string is empty. "0" is not empty, so it was being evaluated as true. Since you are going !geo_select_val, it never goes in.
Caveat: this fix will only work if you make sure all values are numbers. If that's not the case, check for equality with "0"
Here's the code you're asking about:
$('#post-form').click( function() {
var geo_select_val = $('select[name=g_country\\[1\\]]').val();
if(!geo_select_val) {
var geo_url_val = $('input[name=g_url\\[1\\]]').val();
if(geo_url_val != "http://google.com") {
$('#notification').html("You need to enter a valid url");
}
}
});
When I set a breakpoint in this click function and then click on the Post Form div, geo_select_val comes back as "0" which means that if(!geo_select_val) will fail because geo_select_val does have a value so the first if condition will never be executed.
Perhaps you want the first if condition to be:
if (geo_select_val != "0") {
which will tell you if some other value besides the default has been selected (assuming you add other options to that select tag with different values).
I am trying to make a condition where [i] is a value for data.length, the problem is that everything works okay when there are more than 1 value, but when theres only 1 value, the script doesnt work.
out.href = data[i].href;
out.innerHTML = data[i].alt;
out.appendChild(document.createElement('br'));
}
}
Explanation:
When data.length is more than 1, the result will be object1.href, object2.href, etc.
But when the returned query is only of 1 value, i want it to write just "object.href" without the [i] in it, because this works with yql and when yql returns only 1 object, the object number is direct, doesnt have any value. Instead of object1.href, there will only be object.href but the script keeps placing the value in object[i].href thus failing when only 1 result is returned.
Is there any if...else method for this?
Check the count value which is returned with every YQL response.
if (o.query.count == "1") {
data = [data];
}