Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

adding multiple functions to button

Posted on 2010-11-22
11
Medium Priority
?
541 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
Quiz: What Do These Organizations Have In Common?

Hint: Their teams ended up taking quizzes, too.

 
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 1000 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 1000 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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)
Suggested Courses

730 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