• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 550
  • Last Modified:

adding multiple functions to button

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
stargateatlantis
Asked:
stargateatlantis
  • 4
  • 2
  • 2
  • +2
2 Solutions
 
leakim971PluritechnicianCommented:
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
 
claracruzCommented:
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
 
claracruzCommented:
argh!!!  

@leakim971: u were in b4 me.. Ah well!
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
leakim971PluritechnicianCommented:
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
 
leakim971PluritechnicianCommented:
>argh!!!  
>@leakim971: u were in b4 me.. Ah well!

@claracruz see you on the next "fight" ;-))
0
 
stargateatlantisAuthor Commented:
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
 
leakim971PluritechnicianCommented:
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
 
ikbentomasCommented:
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
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
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
 
stargateatlantisAuthor Commented:
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
 
Shahzad Fateh AliWeb Solutions Architect & Technical Project Manager- VentureDive (Pvt) LtdCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 4
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now