jQuery onclick() function within a for loop - javascript

This is probably a simple jQuery/js question but I'm a novice at this and could
use some help.
function launchResultViewer(){
var elen =$MP.data.REG_AS_RS.ASSIGNEE.length;
for (i = 0 ; i < elen ; i++)
{var dEventid = $MP.data.REG_AS_RS.ASSIGNEE[i].EVENT_ID;
var objPVViewerMPage = window.external.DiscernObjectFactory("PVVIEWERMPAGE"); objPVViewerMPage.CreateProcViewer(patientId);
objPVViewerMPage.AppendProcEvent(dEventid);
objPVViewerMPage.LaunchProcViewer(); } }
function OnClickForm(){
var xlen =$MP.data.REG_AS_RS.ASSIGNEE.length;
for (i = 0 ; i < xlen ; i++){
var dOrderid = $MP.data.REG_AS_RS.ASSIGNEE[i].ORDER_ID;
<a href='#'title ="+dOrderid+" onclick='javascript:launchResultViewer(\"" + dOrderid + "\");'>Order</a>"
$('#clickme').click(function(){ ,} }
Say there is two elements in "i" every time I click on the link two screens open up. Each link should only open up once, what am I missing in click function?
Any help would be great.

your first problem is writing your js inline. get rif of the onclick anchor, thats what the #click me event listener is for. in the click me function put what ever action you want it to do there, and get rid of all other anchors, your code is not totally full because you have an empty function at the bottom, but I can almost bet you are calling the same function twice.
change
Order
to order
( your going to have to css it to make it have anchor behavior)
<script>
$('#clickme').click(function(){
launchResultViewer(\"" + dOrderid + "\");
});
</script>

Related

Having trouble getting my HTML onload to call my JS function

I have a function that should be called whenever my html page loads. The <body> tag should call the startAdPage() function. However, nothing at all happens. I am not completely sure why. Any suggestions? Here is the <body> call in my HTML page
<body onload="startAdPage();">
Next, here is my startAdPage() function, as well as the two functions it calls. Those two aren't completely finished yet. One of them is supposed to create a small image gallery slide show. The other is supposed to create a countdown from 10 - 1 before displaying a separate web page. Neither work yet, so any advice on them would also be appreciated, though they aren't my main focus yet.
function startAdPage(){
setInterval(changeAd(), 2000);
setInterval(startCountdown(), 1000);
}
Here is changeAd()
function changeAd() {
for(var i = 1; i < 4; i++){
document.images[0].src = "images/pic" + intNumber + ".jpg";
}
}
Lastly, startCountdown(). I haven't made the webpage that I said this function calls yet
function startCountdown() {
window.alert('Test');
for(var i = 10; i >= 1; i++){
document.getElementById("countdown").value = i;
}
}
Your problem is right here:
document.images[0].src = "images/pic" + intNumber + ".jpg";
You refer to intNumber but you should be using i instead. So change the above to
document.images[0].src = "images/pic" + i + ".jpg";
and your function will be called.
You should consider removing the onload in the body tag and do a
window.onload = startAdPage;
instead - to keep your html and Js logic separate.
Also, your countdown logic is wrong - you want to decrement i, not increment:
var i = 10; i>0; i--

Greasemonkey popup loop not waiting for load-event listener

I'm writing a Greasemonkey script to automatically delete my notifications from a site, based on words I enter into a search box.
The delete "button" is basically a link, so I'm trying to open the first link in a new tab. Then, after it loads enough, open the rest of the links, one by one, in that same tab.
I figured out how to get the links I needed and how to loop and manipulate them. I was able to grab the first delete-link and open it in a new tab. I added an event listener to make sure the page was loaded before going to the next link.
I finally made that work so added my search box and button. Then I had to figure out how to wrap the whole thing in the event listener again.
So, I now have the whole thing working, except only the last link loads.
All links are going to my waitFor function so they should open, so it seems the event listener isn't working so it goes through the loop too fast and only the last link loads.
How do I make this script not continue the loop until the previous loaded page is fully loaded?
Complete code except for box and button creation:
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0]
var myrows = mytable.rows
//function openLinkInTab () {
//mywin2.close ();
//}
var mywin2;
mywin2 = window.open ("http://www.aywas.com/message/notices/test/", "my_win2");
var links;
var waitFor = function (i) {
links = myrows[i].cells[1].getElementsByTagName ("a");
mywin2 = window.open (links[0].href, "my_win2");
}
var delnotifs = function () {
var matching;
var toRemove;
toRemove = document.getElementById ('find').value;
alert (toRemove)
for (i = 0; i < 10; i++) {
matching = myrows[i].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
mywin2.addEventListener ('load', waitFor (i), false);
}
}
}
searchButton.addEventListener ('click', delnotifs, true);
So, why isn't it waiting for `mywin2.addEventListener('load', waitFor(i), false);`? I have a feeling it's something extremely simple that I'm missing here, but I just can't see it.
I also tried mywin2.addEventListener('load', function(){waitFor(i)}, false); and it still does the same thing, so it's not a problem of being a call instead of a pointer.
Swapping mywin2.addEventListener('load', waitFor(i), false); for
if (mywin2.document.readyState === "complete") { waitFor(i)} doesn't work either.
And while I'm at it... every time I see code looping through a list like this it uses
for(i=1;i < myrows.length;i++)
Which was skipping the first link in the list since arrays start at zero. So my question is, if I switch 'i' to zero, and the loop only goes while 'i' is < length, doesn't that mean it won't go through the whole list? Shouldn't it be
for(i=0;i != myrows.length;i++)
When you open a popup (or tab) with window.open, the load event only fires once -- even if you "open" a new URL with the same window handle.
To get the load listener to fire every time, you must close the window after each URL, and open a new one for the next URL.
Because popups are asynchronous and you want to load these links sequentially, don't use a for() loop for that. Use the popup load status to "chain" the links.
Here is the code to do that. It pushes the links onto an array, and then uses the load event to grab and open the next link. You can see the code in action at jsFiddle. :
var searchButton = document.getElementById ('gmPopUpBtn');
var mytable = document.getElementById ('content').getElementsByTagName ('table')[0];
var myrows = mytable.rows;
var linksToOpen = [];
var mywin2 = null;
function delnotifs () {
var toRemove = document.getElementById ('find').value;
for (var J = 0, L = myrows.length; J < L; J++) {
var matching = myrows[J].cells[0].innerHTML;
if (matching.indexOf (toRemove) > 0) {
var links = myrows[J].cells[1].getElementsByTagName ("a");
linksToOpen.push (links[0].href); //-- Add URL to list
}
}
openLinksInSequence ();
};
function openLinksInSequence () {
if (mywin2) {
mywin2.close ();
mywin2 = null;
}
if (linksToOpen.length) {
var link = linksToOpen.shift ();
mywin2 = window.open (link, "my_win2");
mywin2.addEventListener ('load', openLinksInSequence, false);
}
}
searchButton.addEventListener ('click', delnotifs, true);
See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener.
The second argument of the addEventLister function must be a pointer to a function and not a call.

How to change the function called by a dynamically created button?

I was making a little game in JavaScript when I ran into a problem. In this game I create a hundred buttons using a for() loop. Eventually I want every button to call a function called 'click' and send it an int so it knows what button is pressed. So for instance when button four is pressed click(4) is called. First I tried this:
object.onclick = "click(4)";
That obviously didn't work so i searched the interwebs and fount an answer to this question on your site.
object.onclick = function() {click("4");}
I tried that (with and without the ';' at the end) but it doesn't seem work.
A more complete overview of the dummy code:
<script type="text/javascript">
document.getElementById('myContainer').innerHTML += '<input id="tmp" type="button" value="button">';
documengetElementById('tmp').onclick = function() {tmpFunc("bla");}
function tmpFunc(vari){
alert(vari);
}
</script>
The element myContainer is 100% empty!
Remember, this is just dummy code to try it out. I could do this waaaaay easier but I tried to simplify it first so you don't have to look at my messy code.
So what is the best way to call a function from a button you have created in a for loop? If you know a way to do it totally different from the one I use just post it, I don't care how it gets solved! Although I'd also like somebody to explain why this isn't working.
Hope I didn't ask a question already answered, as far as I know I'm using the solution given for this problem in another post.
------------UPDATE-------------
Changed it a bit after getting an answer from somebody. This is the current code, select() isn't executed when a button is pressed. Here's the complete JavaScript code so you can copy-paste it if you want to play around with it.
<script type="text/javascript">
function addButtons(){
var disabled = false;
for(var i = 1; i <= 100; i++){
currentButton = '<input id="tmp" type="button" onclick="select(\''+i+'\')">'
document.getElementById('myContainer').innerHTML += currentButton;
document.getElementById('tmp').id = 'btn'+i;
gb(i).disabled = disabled;
gb(i).style.width = "60px";
gb(i).style.height = "60px";
gb(i).style.fontSize = "25pt";
function alerts(nr){
alert("test");
}
if(i%10 == 0){
document.getElementById('myContainer').innerHTML = document.getElementById('myContainer').innerHTML + '<br />';
}else{
if(disabled){
disabled = false;
}else{
disabled = true;
}
}
if(i == 60){
gb(i).value = 'O';
gb(i).style.color = "blue";
}
if(((i-1)%10 == 0) && !(gb(i).disabled)){
gb(i).value = 'X';
gb(i).style.color = "red";
}
}
}
function select(nr){
alert("Bla!"+nr);
gb(nr).style.height = "100px";
}
function gb(ButtonNrVanHetButton){
return document.getElementById('btn'+ButtonNrVanHetButton);
}
addButtons();
</script>
Most parts aren't very interesting for solving the problem (style etc) It's supposed to look like a checkerboard.
------------UPDATE-------------
Solved! Don't use functions the javascript library already uses for other stuff like: 'select()'. Thx to everybody who tried to help!
If you are looping to create the buttons, why don't you add an onclick to the button?
for instance
<script>
// your function
function tmpFunc(vari)
{
alert(vari);
}
// end your function
// define xBUTTONS
xBUTTONS = '';
for (i=0; i<100; i++)
{
// loop buttons
xBUTTONS += '<input id="tmp" type="button" value="button" onclick="tmpFunc(\''+i+'\')">';
}
// insert buttons into myContainer
document.getElementById('myContainer').innerHTML = xBUTTONS;
</script>
first off, always attach events by using addEventListener. second, if you add an id to the button you dynamicly generate you can do something like this;
function click(){
alert(this.id+" clicked");
}
var but;
for (var i=0,e=100,i<e;++i){
but=document.createElement("input");
but.id=i;
...//make it into your button
but.addEventListener("click", click, false);
document.body.appendChild(but);
}

Write on html on load

I have created a function who tracks on which slide I am currently on and display the result
e.g. If I am on slide 2 of 3 it will display 2/3
my problem is that right now it is set to do that every time I click the forward arrow but it displays nothing on page load.
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
I am trying to find out how to execute this function on page load and where to put it in my code. I am currently learning Javascript through Codecadamedy so I have a basic knowledge of Javascript but I am not enough fluent right now to figure this one out.
Here is a link to the current non working code : http://www.soleilcom.com/metacor_dev/our-plants.php
It looks like you are using jQuery. To execute a function on DOM load in query, do this:
$(document).ready(function() {
/* your code */
});
In your case, that would be:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
});
});
For things like most event handlers, and most other things, initializing at DOM load is good enough. If your code needs to take account for rendered elements or rendered heights, use $(window).load() instead. (In your case DOM load is fine).
Note that this will just establish the click handler at load time. To also run it once, you can do it automatically by either calling the function yourself or triggering a click. To call it yourself, first define another function. The use the function in both the click handler and in one immediate call:
$(document).ready(function() {
var forward = function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}
$('.forward').click(forward);
forward();
});
Or to trigger it yourself, just define the click handler and trigger a click programatically:
$(document).ready(function() {
$('.forward').click(function() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
$("#bottom-image").html(current + "/" + count) ;
}).click();
});
It looks like you are using jQuery, so you would use this:
$(document).ready(function(){
// Code here
});
Or, you can use the shortcut:
$(function(){
// Code here
});
Read more about this on the jQuery website
If you give the function a name, then you can use it multiple times:
$(document).ready(function() {
// Bind to click event
$('.forward').click(forwardSlide)
// Execute function on page load
forwardSlide();
});
function forwardSlide() {
var current = $('#slider').data('AnythingSlider').currentPage; // returns page #
var count = $("#slider").children().length - 2;
};
Is this what you're looking for?

JavaScript Timed Image Swap Need Help

So in my script I have...
<script type="text/javascript">
var images = new Array();
var numImages = 3;
var index = 0;
function setupSwapper() {
for (i = 0; i < numImages; i++) {
images[i] = new Image(266, 217);
images[i].src = "images/image" + i + ".png";
}
setTimeout("swapImage()", 5000);
}
function swapImage() {
if (index >= numImages) {
index = 0;
}
document.getElementById('myImage').src = images[index].src
index++;
setTimeout("swapImage()", 5000);
}
</script>
And then I have <body onload="setupSwapper()"> to setup the body.
and <img width=266 height=217 id="myImage" name="myImage" src="images/image0.png"></img> elsewhere in my document.
Only the initial image (image0.png) is showing up. I'm probably blind from having looked at this so long. The images are not swapping.
Use FireBug or a similar tool for debugging what's going on:
Does the img DOM element in fact gets its src changed ?
Do you see any network activity trying to load the images ? does it succeed ?
Set up breakpoints in your code and see what happens in the debugger
BTW - You can use setInterval instead of setTimeout - it sets a repeating timer
You're missing the () in the definition of "setupSwapper".
Also it's setTimeout, not setTimeOut.
Finally, get rid of the "type" attribute on your <script> tag.
You might want to start "index" at 1 instead of 0.
The way to go:
setTimeout(swapImage, 5000);
[FORGET] the type attribute has nothing to do with it
[FORGET] the index has nothing to do with it
[OPTIONAL] remove "name" attribute from the image (useless)
[OPTIONAL] close image tags like <img />
Note: 2-5 is about correctness. Only the first one is important to get it work.
Get Firebug, use it's debugger to put breakpoints inside swapImage to see if it is hit after the timeout. Another way is to use the console.* apis to see what's happening(e.g. console.log).

Categories