Adding control ID's into Global Array variable - javascript

I am pretty sure I understand why this is not working. I think its because at the time the controls are trying to be found, the page has not rendered them yet.
Assuming that is the case, My question is how can I set these Arrays after the page has been fully loaded and still access them globally?
If I set the Arrays in the function my code works but it seems like a waste to find them like that as there will end up being 12 controls per array and the function really only needs to access 2 controls.
Here is some of my code:
//The controls in the following arrarys can not be found at this point of execution.
//If I put these Arrays into my function , the code works and the controls are found.
var RadRatingArray = [$find("<%= RadRating_Rating0.ClientID %>"), $find("<%= RadRating_Rating1.ClientID %>")];
var RadRatingNAArray = [$find("<%= RadRating_NA0.ClientID %>"), $find("<%= RadRating_NA1.ClientID %>")];
var RadTextBoxArray = [$find("<%= RadTextBox_Comment0.ClientID %>"), $find("<%= RadTextBox_Comment1.ClientID %>")]
//This function is called when the NA rating control is clicked. It clears the rating control and sets a number of other elemnts on the page.
function ClearRadRating_Rating(sender, args) {
var Number = sender.get_id().slice(-1);
var IntNum = parseInt(Number, 10);
if (sender.get_value() !== 0) {
RadRatingArray[IntNum].set_value(0);
}
SetSelectedRating(sender, RadTextBoxArray[IntNum], "Message" + [Number], "CallOut" + [Number]);
}
Thanks!

Related

I am trying to stop my function from displaying the same object twice when clicking a button

I have for quite some time now been trying to figure out how I can stop my code to print the same quote twice.
Also, when every single object in the array has been printed out, I'd like for it to reset somehow. So that you can browse through the quotes once you've gone through all of them.
This is the essential parts of my code:
document.getElementById('loadQuote').addEventListener("click", printQuote, false);
The printQuote function simply contains information that's accessing information from my array:
var randomObjectNumber = getRandomQuote();
var html = "<p class='quote'>"
+ quotes[randomObjectNumber].quote +
"</p>";
document.getElementById('quote-box').innerHTML = html;
One random object is displayed each time you click the eventListener:
function getRandomQuote () {
var randomObjectNumber = Math.floor(Math.random() * quotes.length );
return randomObjectNumber;
}
I have some ideas on how to do this and I have tried them but without success. I tried giving each object a boolean property but I can't really seem to assign each property a boolean value without messing the printQuote function up.
I also tried assigning the object displayed to a different array but the same problem occurred there.
I feel like there is some concepts around the eventListener that I don't fully understand, because every time I try to manipulate a displayed object I just end up changing every single object.
This is what a typical object in the array looks like by the way:
{quote : "Darkness is merely the absence of light"}
(I also have other properties assigned to the object but i feel like presenting them would be redundant)
If someone could explain, or give me a hint, on how to solve this problem I've been struggling with for some time.
Some hints would be greatly appreciated!
Have a nice day.
Sebastian.
EDIT: All code: https://jsfiddle.net/fusqb7hz/
Basically what you need:
Create a separate array that will store all quotes that you've already used.
Remove quote from initial array.
Check if you still have quotes in initial array, if not, get them back from backup array.
The problem is that you call addEventListener twice:
//Let's developers create multiple eventListeners without being redundant.
function onClicking (printFunction) {
document.getElementById('loadQuote').addEventListener("click", printFunction, false);
}
onClicking(printColor);
onClicking(printQuote);
by calling onClicking twice you make the click happen twice, so addEventListener is added twice, meaning one click counts as two.
Change the above code for this:
//Let's developers create multiple eventListeners without being redundant.
document.getElementById('loadQuote').addEventListener("click", function(){
printColor();
printQuote();
});
Here is the jsfiddle:
https://jsfiddle.net/fusqb7hz/3/
I think the easiest approach is to shuffle your quote array and then go through them one by one. This gives you the next "random" as yet unseen quote. The only part I'm not keen on is this shuffler (a derivation of Fisher Yates) modifies the original quote array. You might not care about that though.
// --------------------------------
// A bunch of quotes
// --------------------------------
var quotes = [];
quotes.push({quote : "Darkness is merely the absence of light"});
quotes.push({quote : "quote 2"});
quotes.push({quote : "quote 3"});
quotes.push({quote : "quote 4"});
quotes.push({quote : "quote 5"});
// --------------------------------
// --------------------------------
// Your favorite array shuffle utility
// --------------------------------
var shuffle = function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
// --------------------------------
// --------------------------------
// construct a function to get a random unseen quote until
// all quotes have been seen. Then reset...
// --------------------------------
var getQuote = (function(quotes, shuffle){
var current = 0;
var get = function(){
if ( !quotes || !quotes.length ) { return ""; }
if ( current >= quotes.length ){ current = 0; }
if ( current === 0 ){
console.log("randomizing quotes...");
shuffle(quotes);
}
return quotes[current++].quote;
};
return get;
})(quotes, shuffle);
// --------------------------------
var printQuote = function(){
document.getElementById('quote').innerText = getQuote();
};
document.getElementById('loadQuote').addEventListener("click", printQuote, false);
<div id="quote"></div>
<button id="loadQuote">get quote</button>

Passing more than two values in javascript function

In my jsp page I have a javascript function for a button click.In that I need to pass some values to next jsp page.I can able to pass two values as a parameter but while giving three values its not working.Not working means control is not going next page when click on button.
This one works fine
window.location.assign("gt_Iba2?value="+uri+"&len="+<%=height%>);
This is not working
window.location.assign("gt_Iba2?value="+uri+"&len="+<%=height%>+"&SelectedValue="+<%=typeNameToPass%>);
EDIT
typeNameToPass is a string value i'm getting from previous jsp page.
String typeNameToPass =request.getParameter("value");
My javascript function
<SCRIPT LANGUAGE="JavaScript">
function gt2()
{
var pqr="100";
var arr=new Array();
var x=<%=height%>;
var attstr=null;
for(var t=0;t<x;t++)
{
var a="inputText"+t;
var e=document.getElementById(a);
var val= e.value;
if(val.indexOf(",") !== -1){
alert("Legal value Constraint can't allow comma");
return;
}
arr[t]=val;
if(t==0)
{
attstr=arr[t]+",";
}
if((t!=x)&&(t!=0))
{
if(t==x-1)
{
attstr+=arr[t];
}
else
{
attstr+=arr[t]+",";
}
}
}
var uri=encodeURIComponent(attstr);
window.location.assign("gt_Iba2?value="+uri+"&len="+<%=height%>+"&SelectedValue="+<%=typeNameToPass%>);
I don't know what's wrong here.Any ideas would be much helpful
Try that:
window.location.assign("gt_Iba2?value="+uri+"&len=<%=height%>&SelectedValue=<%=typeNameToPass%>");
Your code works for height, probably because it is number. Then you will get in JS something like "[...]&len="+80, but if typeNameToPass is a string value you will get "[...]&len="+80+"&SelectedValue="+someString - unless someString is a variable, you will get error.

Random Items and linking

Sorry if the post was unclear, I’ll try to explain as best I can. I’m creating a social psychology experiment online, and I need a function to be able to select at random different names (like John, Mike, Alex etc.). While looking for help online I found this code:
function swapImages(){
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery.active').next() : $('#myGallery img:first');
$active.fadeOut(function(){
$active.removeClass('active');
$next.fadeIn().addClass('active');
});})
Using this code and the "mousetrap" library I was able to change the name when a key is pressed. But I have no clue on how I can make the names appear randomly (this means, not in the order they are on the code, but different every time I do it). And after 40 different names, I need to link to another html page.
Thanks for the help, and sorry if my last post was confusing.... This is my first approach to programing :)
Old post:
Im quite new to the programing world, i need some help making this code select random items, not in the order I put them on. Also, i got this from the web and i need it to stop after 40 items and link to antoher page.
Thanks for the help
If you simple need to select random names - selection from array using Math.Random is the simplest approach:
var names = ["John", "Mike", "Peter", "Sid", "Homer"]
var idx;
do {
idx = parseInt(names.length * Math.random());
alert(names[idx]);
names.splice(idx, 1);
} while (names.length > 0)
Basically it generates random index within boundaries of array's length, selects element at that index and then removes the element from array. Loop exits when there're no more elements to display.
Demo: http://jsfiddle.net/4NNTA/1/
If your list has over 40 items and you need to exit after 40 - add a counter and condition to the while. After exiting the loop you can redirect to another page by setting location.href to URL of page you want to go to.
UPDATE This is a function that used revised code above. It lets you specify arbitrary number of names:
var Names = function () {
var data;
var counter;
function initData() {
data = ["John", "Mike", "Peter", "Sid", "Homer"]
}
this.init = function (c) {
counter = c;
initData()
}
this.getName = function () {
if (counter === 0) {
return ""
} else {
if (data.length === 0) initData();
var idx = parseInt(data.length * Math.random());
var sName = data[idx]
data.splice(idx, 1);
counter--;
return sName
}
}
}
Inside of function initData you can specify array of names. Then you initialize it by passing number of names you want to display (this example initializes it to 40):
var myNames = new Names();
myNames.init(40);
And then every time you call
myNames.getName()
It will give you next random name. The names will not repeat until data is exhausted - then the array is reinitialized and random un-repeated names begin again. When all 40 names are retrieved - function returns empty string, which you can check and act accordingly.

Track which JSON objects have been output

I'm outputting 20 or so JSON objects randomly by setting the index to a randomNumber() initially when the page is loaded.
I'm refreshing each JSON object individually that has already been output on a timeInterval.
To keep track of which JSON items have been output I am storing the index of each item into an array via arrUsed.push[index]
Now trying to write the function that will update() each JSON objects individually and am currently stuck on how I can update the each div with the information from a new JSON object that has not already been output (pushed to the arrUsed[]).
Here's the function I have so far:
function reloadItems() {
var itemTotal = $('div.item').length; // Total number of items loaded initially
var randomNumber=Math.floor(Math.random()*301) //returns number
index = randomNumber; // Sets index to be used in JSON data to random number
}
The array that contains the already output index's is declared globally: arrUsed = []; Each item that is output initially when the page load is being stored to the array fine, so that part is covered. It's a matter of choosing a random JSON object, checking to ensure it is not in the array/not been output already, and then updating the div on the page.
Here's the previous question that has led me to this point
Here's a working example of a JSON/AJAX Ticker:
http://ticker.weisser.co/
Per twhyler's specification, it randomly swaps an item every 4.5 seconds, keeping track of ones that have already been seen. Once they've all been seen, it starts over again:
Code Files:
default.html (Main Program)
template.html (Product Template)
UK.top.20.html (JSON Data)
ticker.js (jQuery)
ticker.css (Style Sheet)
First, we should store template.html in our global template variable and fire the getJson() function:
template = '';
....
$(document).ready(function () {
$.get('template.html', function(html) { template = html; getJson(); });
});
Then, we'll store the JSON into our data variable and fire the initialize() function:
data = ''; // JSON data will be stored here
myurl = 'UK.top.20.html';
....
function getJson() {
$.getJSON(myurl, function (JSON) { data = JSON; initialize(); });
}
Here, we'll call the load() function 3 times to populate our 3 product div's with data right away. Then we set i back to 2 (that's so it will change the 3rd DIV first), and schedule tick() to fire in 4.5 seconds:
tick_time = 4500;
....
function initialize() { // Start with the first 3
for (i = 1; i < 4; i++) { load(); }
i = 2;
setTimeout('tick()', tick_time);
}
Before we explain the load() function, let's talk about `String.prototype.f' at the bottom of the script:
String.prototype.f = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; }); };
This function works similar to String.Format(formatstring, arg1, arg2, arg3...) in C# or sprintf($formatstring, arg1, arg2, arg3...) in PHP. Here's an example:
formatstring = 'Roses are {0}, Violets are {1}, String.Format {2} and so do {3}!';
result = formatstring.f('red', 'blue', 'rocks', 'you');
alert(result);
So as you can see, this String.prototype.f function comes in very handy!
The first thing the load() function will do is set rid = randomId();. Let's take a look at the randomId() function next. The first thing it does is get a number from 1-20 (based on the length of our JSON data). Then, it checks to see if our seen array is the same size as our JSON data, and if it is - it sets it back to 0. Next it makes sure that our rid hasn't been seen recently, and if it has, the function recursively calls itself again till it gets a unique random id. Otherwise, we store the rid in our seen array and return the value.
function randomId() {
rid = Math.floor(Math.random() * data.results.length);
if (seen.length == data.results.length) { seen.length = 0; }
if ($.inArray(rid, seen) == -1) {
seen.push(rid);
return rid;
} else { return randomId(); }
}
Next in our load() function after getting that random ID, we setup item and plat as convenient shortcuts. plat_html is a temporary storage place for the Platform elements. The for-loop looks at all the Platform data in our JSON and uses our String.Format function to fill our plat_html string.
Finally, we allow the current value of i (which is global) determine which #product_ gets updated, and template.f fills our template with JSON data which is done with a smooth jQuery animation thanks to .fadeIn().
function load() {
rid = randomId();
item = data.results[rid];
plat = item.Platform;
plat_html = '';
for (var j = 0; j < plat.length; j++) {
plat_html += plat_fmt.f(
plat[j].Hardware,
plat[j].Market
);
}
$('#product_' + i).html(
template.f(
item.Image,
item.id,
item.AgeRating,
item.WikiUrl,
item.Title,
item.Source,
item.Genre,
plat_html
)
).fadeIn();
}
Lastly, let's take a look at the recursive tick() function. It begins by incrementing our global i variable and setting it back to 1 when it reaches 4. Then we perform an animated fadeOut() on our #product_ element and wait till it's finished till we call load() again. Then, it schedules itself to run again in another 4.5 seconds.
function tick() {
i++; if (i == 4) { i = 1; }
$('#product_' + i).fadeOut(function() { load(); });
setTimeout('tick()', tick_time);
}
That's it!
Use $.inArray(): http://api.jquery.com/jQuery.inArray/
$.inArray(indexInQuestion, arrUsed);
It will return -1 if the element is not in the array, so you will know wether indexInQuestion was already added to arrUsed.

Trouble with Variable value in function

I have the following script where a variable gets its value from an input field, however when I run my function its not working, returns nothing. Im new to JS so im unsure if it needs to be part of a function *even though Ive tried this with no luck) or what...
/////////////////////////////////////////////////////////////////////
// Variables
// Content/SLA
var ContentMinutes = '';
var ContentMinutesSelector; // Switch Case
var ServiceLevel = 5;
var NoOfFrames = 2;
// Render Time (Hairier the Better)
var AvgFrameRenderTime = '';
var AvgFrameRenderTimeSelector = 10; // Switch Case
var CoresInTest = document.getElementById('CoresInTest').value;
// Other
var EstimatedCoreHours = NoOfFrames * CoresInTest * AvgFrameRenderTimeSelector;
// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;
/////////////////////////////////////////////////////////////////////
// Functions
function CalculateEstimate() {
// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));
// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed( 2));
}
my PriceEstimate and EstimatedCoreHours fields are both just empty divs, <div id="EstimatedCoreHours"></div>, My calculations work if i define a value for the variable as opposed to document.getElementById so I believe I must need to run a function or something to update all the vartiables?
But if I set...
var CoresInTest = document.getElementById('CoresInTest').value;
to
var CoresInTest = 10;
Then it works fine...
Its not actually my return, the problem is my variables arent calling, IF i define them with a number then it works.
I guess you need to do something like this, if you are looking to get calculated data in your div.
document.getElementById("PriceEstimate").innerHTML=parseInt(CostEstimate.toFixed(2));
// Estimate Core Hours
document.getElementById("EstimatedCoreHours").innerHTML=parseInt(EstimatedCoreHours.toFixed(2));
If var CoresInTest = 10; works fine, then your code is placed wrong.
What element is CoresInTest? is it a text field? and if so is this script placed or called before the element renders? then you will have to reinitialize that variable.
If PriceEstimate and EstimatedCoreHours are elements you should use the value property
this might work for you:
document.getElementById("PriceEstimate").value=parseInt(CostEstimate.toFixed(2),10);
document.getElementById("EstimatedCoreHours").value=parseInt(EstimatedCoreHours.toFixed(2),10);
If var CoresInTest = 10; makes it work fine, then it must be something to do with document.getElementById('CoresInTest').value - so why isn't that working? Is it a drop down list? Instead of us guessing, tell us.

Categories