Solved

adding multiple functions to button

Posted on 2010-11-22
11
531 Views
Last Modified: 2012-06-22
Lets say you have the following function.  What I am having problem is trying to figure out of adding this function to 20 buttons.  Instead of saying button1.click function you just do a loop and add the events to all 20 buttons.  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(document).ready(function () {
        $("#btn1Start").click(function () {
				// MODIFICATION: expire times should be entered like ['00:00:00'] seperated with comma's
                timer1 = setInterval("$.do_time('timer1',['00:00:03','00:00:06','00:00:09','00:00:15'])", 1000);
                $(this).attr("disabled", true);
        });
        $("#btn2Start").click(function () {
                timer2 = setInterval("$.do_time('timer2', ['00:00:05'])", 1000);
                $(this).attr("disabled", true);
        });
        $("#btn3Start").click(function () {
                timer3 = setInterval("$.do_time('timer3')", 1000);
                $(this).attr("disabled", true);
        });
        totaltimer = setInterval("$.displayTotal('totaltimer')", 1000);
});
//Timer JQuery function
(function ($) {
   totaltime = "00:00:00";
   		// MODIFICATION: changed expireTime to times.
        $.do_time = function(timerID, times) {
                
                var time = ($("#" + timerID).html()).split(':');
                var hour = parseInt(time[0], 10);
                var minute = parseInt(time[1], 10);
                var second = parseInt(time[2], 10) + 1;
                
                var ttime = totaltime.split(':');
                var thour = parseInt(ttime[0], 10);
                var tminute = parseInt(ttime[1], 10);
                var tsecond = parseInt(ttime[2], 10) + 1;
                
                if (second > 59) {
                        second = 0;
                        minute++;
                }
                if (minute > 59) {
                        minute = 0;
                        hour++;
                }
                if (tsecond > 59) {
                        tsecond = 0;
                        tminute++;
                }
                if (tminute > 59) {
                        tminute = 0;
                        thour++;
                }
                
				// MODICIFICATION: loop over all times in stead of one time
				if(times){
					for(i in times){
						var etime = times[i].split(':');
						var ehour = parseInt(etime[0], 10);
						var eminute = parseInt(etime[1], 10);
						var esecond = parseInt(etime[2], 10);
						expired = false;
						if(ehour<hour) {
								expired = true;
						}
						else if(ehour==hour) {
								if(eminute<minute) {
										expired = true;
								}
								else if(eminute==minute) {
										if(esecond<=second) {
												expired = true;
										}
								}
						}
						
						if(expired) {
							//MODIFICATION: use a switch to control different color states.
							var steps = 5;
							progress = Math.floor((parseInt(i,10)+1)/times.length*steps)-1;
							switch(progress){
								case 0: $("#" + timerID).css("background-color", "yellow"); break;
								case 1: $("#" + timerID).css("background-color", "#FFC000"); break;
								case 2: $("#" + timerID).css("background-color", "#FF8000"); break;
								case 3: $("#" + timerID).css("background-color", "#FF4000"); break;
								case 4: $("#" + timerID).css("background-color", "red"); break;
							}
							
						}
						
					}
				}
                
                time = (hour>9?hour:'0'+hour) +':'+ (minute>9?minute:'0'+minute) +':'+ (second>9?second:'0'+second);
                $("#" + timerID).html(time);
                totaltime = "" + (thour>9?thour:'0'+thour) +':'+ (tminute>9?tminute:'0'+tminute) +':'+ (tsecond>9?tsecond:'0'+tsecond);
        } //End Doo time function
        $.displayTotal = function(labelID) {
                $("#" + labelID).html(totaltime);
        }
})(jQuery);
</script>
</head>
<body>
<table width="300">
   <tr>
      <td id="timer1">00:00:00</td>
      <td><input type="button" id="btn1Start" value="button1" /> (Expires in 15 seconds)</td>
   </tr>
   <tr>
      <td id="timer2">00:00:00</td>
      <td><input type="button" id="btn2Start" value="button2" /> (Expires in 5 seconds)</td>
   </tr>
   <tr>
      <td id="timer3">00:00:00</td>
      <td><input type="button" id="btn3Start" value="button3" /> (Does not expire)</td>
   </tr>
   <tr>
      <td id="totaltimer">00:00:00</td>
      <td></td>
   </tr>
</table>
</body>
</html>

Open in new window

0
Comment
Question by:stargateatlantis
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +2
11 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 34188243
Use the same class (for example myclass) for all the button :

<input class="myclass" type="button" id ="btn1Start" />
<input class="myclass" type="button" id ="btn2Start" />
<input class="myclass" type="button" id ="btn3Start" />

Open in new window


so use :

$(".myclass").click(function() {

Open in new window

0
 
LVL 4

Expert Comment

by:claracruz
ID: 34188265
You could give all the buttons the same classNames and then do like so;-


$(".myButons").click(function () {
      
        });


Bet u r kicking urself its so easy.. :-)
0
 
LVL 4

Expert Comment

by:claracruz
ID: 34188269
argh!!!  

@leakim971: u were in b4 me.. Ah well!
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 82

Expert Comment

by:leakim971
ID: 34188272
You can use the start with selector too : http://api.jquery.com/attribute-starts-with-selector/
and end with : http://api.jquery.com/attribute-ends-with-selector/

$("input[type='button'][id^='btn'][id=$'Start']").click(function() {

Open in new window


0
 
LVL 82

Expert Comment

by:leakim971
ID: 34188285
>argh!!!  
>@leakim971: u were in b4 me.. Ah well!

@claracruz see you on the next "fight" ;-))
0
 

Author Comment

by:stargateatlantis
ID: 34188357
But the question is how would you assign the timer function so that the timer index is all different.  Reason for this you want to have the ability to clear interval timer

This line here

timer3 = setInterval("$.do_time('timer3')", 1000);

timer3 should be a index or something
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34188391
inside you get the button number/id with something like :

$("input[type='button'][id^='btn'][id=$'Start']").click(function() {
     var idNumber = $(this).attr("id").replace(/\D/g,""); // you get 1, 2, 3..., n
     setInterval("$.do_time('timer" + idNumber + "')", 1000);
     // rest of the code
});
0
 
LVL 1

Accepted Solution

by:
ikbentomas earned 250 total points
ID: 34188404
A possible solution would need two changes to your page.
First add a class name to the button with the name of the desired timer.
like this:
<input type="button" id="btn1Start" class="timer1" value="button1" />

The second change would be the $(document).ready function
like this:
$(document).ready(function () {
    $(':input[type=button]').each(function(){   
        $(this).click(function () {
                var timerId = $(this).attr('class'),
                    action = "$.do_time('"+timerId+"',['00:00:03','00:00:06','00:00:09','00:00:15'])"
                window[timerId] = setInterval(action, 1000);
                $(this).attr("disabled", true);
        });
    });
       totaltimer = setInterval("$.displayTotal('totaltimer')", 1000);
});

Open in new window

0
 
LVL 9

Assisted Solution

by:Shahzad Fateh Ali
Shahzad Fateh Ali earned 250 total points
ID: 34194077
Hi,

I have modified your initial code and here is the final solution.
Changes are:
-Times array is stored with the butto in data attribute.
-Second argument for do_time is the element id rather then times array.
- class 'timerButton' has been added to all buttons.

I have tested the above code in IE7&8, Chrome, FF.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
$(document).ready(function () {
	$('.timerButton').click(function(){
		var i = $(this).attr('id').replace(/[^0-9]/g,'');
		setInterval('$.do_time("timer'+i+'", "'+$(this).attr('id')+'")', 1000);
	});
        totaltimer = setInterval("$.displayTotal('totaltimer')", 1000);


});
//Timer JQuery function
(function ($) {
   totaltime = "00:00:00";
   		// MODIFICATION: changed expireTime to times.
        $.do_time = function(timerID, timesEl) {
                
		var times = $('#'+timesEl).attr('data').split(',');
		
                var time = ($("#" + timerID).html()).split(':');
                var hour = parseInt(time[0], 10);
                var minute = parseInt(time[1], 10);
                var second = parseInt(time[2], 10) + 1;
                
                var ttime = totaltime.split(':');
                var thour = parseInt(ttime[0], 10);
                var tminute = parseInt(ttime[1], 10);
                var tsecond = parseInt(ttime[2], 10) + 1;
                
                if (second > 59) {
                        second = 0;
                        minute++;
                }
                if (minute > 59) {
                        minute = 0;
                        hour++;
                }
                if (tsecond > 59) {
                        tsecond = 0;
                        tminute++;
                }
                if (tminute > 59) {
                        tminute = 0;
                        thour++;
                }
                
				// MODICIFICATION: loop over all times in stead of one time
				if(times.length){
					for(i in times){
						var etime = times[i].split(':');
						var ehour = parseInt(etime[0], 10);
						var eminute = parseInt(etime[1], 10);
						var esecond = parseInt(etime[2], 10);
						expired = false;
						if(ehour<hour) {
								expired = true;
						}
						else if(ehour==hour) {
								if(eminute<minute) {
										expired = true;
								}
								else if(eminute==minute) {
										if(esecond<=second) {
												expired = true;
										}
								}
						}
						
						if(expired) {
							//MODIFICATION: use a switch to control different color states.
							var steps = 5;
							progress = Math.floor((parseInt(i,10)+1)/times.length*steps)-1;
							switch(progress){
								case 0: $("#" + timerID).css("background-color", "yellow"); break;
								case 1: $("#" + timerID).css("background-color", "#FFC000"); break;
								case 2: $("#" + timerID).css("background-color", "#FF8000"); break;
								case 3: $("#" + timerID).css("background-color", "#FF4000"); break;
								case 4: $("#" + timerID).css("background-color", "red"); break;
							}
							
						}
						
					}
				}
                
                time = (hour>9?hour:'0'+hour) +':'+ (minute>9?minute:'0'+minute) +':'+ (second>9?second:'0'+second);
                $("#" + timerID).html(time);
                totaltime = "" + (thour>9?thour:'0'+thour) +':'+ (tminute>9?tminute:'0'+tminute) +':'+ (tsecond>9?tsecond:'0'+tsecond);
        } //End Doo time function
        $.displayTotal = function(labelID) {
                $("#" + labelID).html(totaltime);
        }
})(jQuery);
</script>
</head>
<body>
<table width="300">
   <tr>
      <td id="timer1">00:00:00</td>
      <td><input type="button" id="btn1Start" class="timerButton" value="button1" data="00:00:03,00:00:06,00:00:09,00:00:15" /> (Expires in 15 seconds)</td>
   </tr>
   <tr>
      <td id="timer2">00:00:00</td>
      <td><input type="button" id="btn2Start" class="timerButton" value="button2" data="00:00:05" /> (Expires in 5 seconds)</td>
   </tr>
   <tr>
      <td id="timer3">00:00:00</td>
      <td><input type="button" id="btn3Start" class="timerButton" value="button3" data="" /> (Does not expire)</td>
   </tr>
   <tr>
      <td id="totaltimer">00:00:00</td>
      <td></td>
   </tr>
</table>
</body>
</html>

Open in new window

0
 

Author Comment

by:stargateatlantis
ID: 34197694
shahzadfatehali the only problem i don't see where you put the '00:00:03','00:00:06','00:00:09','00:00:15'
0
 
LVL 9

Expert Comment

by:Shahzad Fateh Ali
ID: 34198414
Hi,

its in html button element
<td><input type="button" id="btn1Start" class="timerButton" value="button1" data="00:00:03,00:00:06,00:00:09,00:00:15" /> (Expires in 15 seconds)</td>

Open in new window

0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question