Detect [i] value - javascript

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];
}

Related

getting new nth indexed number of element from an array according to the given nth element in a circular manner

so the problem is simple . here i want to return the new nth element of an array according to the
previous nth element sent by the user.for example
['1','3','5','7','9','11']
if a user sends a value of 3 then I would like to return 7, if the user sends 5 then I would like to return 9 , if they send 7 then 11 and when they send 11 then I want to return 3. basically its like puting the array in a circular mode and return the next element.
here is my code.
var indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
var index=indices.indexOf(uservalue);
return indices[index+index_to_add];
everything here works fine but when the array finishes or nears the end then I get undefined instead of element from the first. how can i get the element from the beginning if the element index is undefined or the array finishes?
Using the Modulo operator:
return indices[(index+index_to_add) % indices.length];
Note: this will only handle the case when uservalue is actually part of the array. You might want to add a clause like if(index === -1) return 'Uservalue not in array.' or throw an error.
If I've interpreted your question correctly, a solution would be to encapsulate the processing within a recursive function, if you're after readable code and are unfamiliar with the Modulo function (doing it this way also makes it easier to change the process in the future):
const indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
console.log(GetElemAtIndex(GetIndex(userValue) + index_to_add));
function GetIndex(userValue) {
return indices.indexOf(userValue); // If this is -1 the user has entered something not in the array
}
function GetElemAtIndex(toFind) {
if (indices.length > toFind) {
return indices[toFind];
}
else {
return GetElemAtIndex(toFind - indices.toLength);
}
}
The modulo function in Taxel's answer is a more efficient way of doing the GetElemAtIndex block.

Replace 'null' values from AJAX call

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

jQuery won't count up variables

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());

difficulty with adding values from html textbox in javascript

Sorry if this is a stupid question. I am a newbie to programming...
I have 3 values from a text input. I want 2 of these values to be stored into separate arrays for later access. finally I want to display a sum of these 3 values in my document.
What am I doing wrong?
Here is my code:
<script>
function displayCurrentBalance() {
var initialBalance = parseFloat(document.getElementById("initialBalance").value);
var inAmounts=[0];
var outAmounts = [0];
inAmounts.push(document.getElementById("amountIn").value);
outAmounts.push(document.getElementById("amountOut").value);
var sumIn = (inAmounts.reduce(function(a, b) {
return a + b[1];
}, 0));
var sumOut = (outAmounts.reduce(function(c, d) {
return c + d[1];
}, 0));
var result = initialBalance + sumIn - sumOut;
document.write(result);
};
displayCurrentBalance();
</script>
document.write(result); will overwrite your document before you even have a chance to enter the values. Make it display a value in another input box, or alert(result).
You should probably attach displayCurrentBalance to an onclick handler of some button, like <button onclick="displayCurrentBalance()">Calculate</button>.
document.getElementById("amountIn").value and similar calls will give you a string. You should use parseFloat or parseInt to convert it to an integer or a float.
You are likely calling the function before the elements are available in the page. Otherwise the script should be below the elements in the page.
You main problem is how you are using reduce. The values returned from the inputs are strings, so convert them to numbers before trying to add them (otherwise you will be concatenating strings, not adding numbers). You should probably validate the values too.
Also, reduce is called with the values of the members of the array, not the array itself (which is the 4th parameter provided to the callback, not the second), so:
var sumIn = (inAmounts.reduce(function(a, b) {
return +a + +b;
}, 0));
Modify the other call to reduce similarly. I don't think you need to provide an initial value since you initialise the array as [0]. Alternatively, keep the initial value in the call and initialise the array as [] (i.e. an empty array).
Rather than using document.write to display the result, better to write it as the value of a read–only input element so you can update it with subsequent calls as the user modifies the values in the other inputs.

JSON.parse() not giving expected result

I have a string that is JSON values separated by /r. It's sort of like records in a DB table. It looks like:
"{"id":"id","hole":"hole","stat":"stat","value":"value"}/r{"id":1354075540949,"hole":"1","stat":"score","value":"4"}/r{"id":1354075540949,"hole":"1","stat":"putts","value":"1"}/r{"id":1354075540949,"hole":"1","stat":"fir","value":"y"}/r{"id":1354075540949,"hole":"1","stat":"gir","value":"n"}/r"
The first row is the column names (id, hole, stat, value) and I just give them the same value. All other rows separated by /r is the actual data.
I split this string by /r, then loop through the result and push the result of JSON.parse() of each element to an array so now I have an array of objects with properties of the given structure (id, hole, stat, value). Everything is working except the 'id' field ends up being true or false instead of the big long number. Why is it doing that?
var tblData = localStorage.getItem(tblName).split("/r");
var data = new Array();
// fill the array
for (i = 1; i < tblData.length - 1; i++)
data.push(JSON.parse(tblData[i]));
[EDIT]
Seems this does work, but there is a jQuery.grep() I run right after this that's setting the id properties to true/false.
var changeRecords = jQuery.grep(data, func);
Where func is:
function (v) { return v.id == gCurrentRoundID && v.hole == gCurrentHole; }
Not sure why it would be setting id to true/false though.
[EDIT2]
Nevermind, I found my error. The function above wasn't the right one and the one I did have only had 1 equal sign for v.id = gCurrentRoundID, which is why it was setting it to true/false.
I would just manually change the whole string to valid JSON. Have it start with a [ and end with a ], then replace all those /rs with commas. The end result should look like
"[{"id":"id","hole":"hole","stat":"stat","value":"value"},{"id":1354075540949,"hole":"1","stat":"score","value":"4"},{"id":1354075540949,"hole":"1","stat":"putts","value":"1"},{"id":1354075540949,"hole":"1","stat":"fir","value":"y"},{"id":1354075540949,"hole":"1","stat":"gir","value":"n"},]"
Then parse that through JSON.parse
Just note that that last trailing comma may cause problems in IE8. If so, you should be able to manually fix that fairly easily. Something like s = s.substr(0, s.length - 2) + ']';

Categories