Jump to content

Which Button was Clicked?


grungefreak

Recommended Posts

<script>

function handleClick(id){

          element= document.getElementById(id);

          if(!element) element= document.getElementsById(id);

          if(element) {

              if(element.name) alert('You clicked ' + element.name);

              else if(element.id)  alert('You clicked somthign that dosent have a name but id of ' + element.id);

              //etc etc etc

          }

          else alert('could not find the element clicked');

}

<script>

<input type='button' id='button1' value='button1' onclick='handleClick('button1')' />

<input type='button' id='button2' value='button2' onclick='handleClick('button2')' />

<input type='button' id='button3' value='button3' onclick='handleClick('button3')' />

 

Link to comment
Share on other sites

well you usually put the javascript on the button like this

<input type='button' value='button1' onclick='alert(this.value + " was clicked");' />

 

not really sure how you can make a global function that catches any buttons click

 

thanks. That works when I pass the code to onClick function.

I am creating a small calculator and will put the code into a function called calc() in the head of my html. I just want a simple way to check which button was clicked and from there I can use if statements to determine what course of action to follow.

 

When I use the 'this.value' code in my function however, it returns 'undefined' for my button for some reason. I 'm sure this is just a simple logic problem.

 

gf

Link to comment
Share on other sites

the this.value that I used in the <input ... /> line represents the value option of the element

 

so you can't use it in a function

if you assign an ID to the button, you can get the button value with

document.getElementById("buttonid").value;

if you want to find it by name, you'll have to use

document.getElementsByName("buttonname")[0].value

but this last method only works if only 1 element in the document has that name.

Link to comment
Share on other sites

the this.value that I used in the <input ... /> line represents the value option of the element

 

so you can't use it in a function

if you assign an ID to the button, you can get the button value with

document.getElementById("buttonid").value;

if you want to find it by name, you'll have to use

document.getElementsByName("buttonname")[0].value

but this last method only works if only 1 element in the document has that name.

Thanks for the help on this but I'm still kinda confused. I can now identify the button in my function but how do I assess whether it was clicked e.g.

 


var addition = document.getElementById("add").value;
var subtraction= document.getElementById("subtract").value;

if (addition){// perform addition}
else if (subtraction){// perform subtraction}

  

 

My problem is that the first test will be true as I am only testing the value of an element. I want to be able to check if it was 'pressed'

e.g.



if (user pressed add) {//then perform addition}

 

I know this is probably simple stuff but i'm new to javascript.

 

gf

Link to comment
Share on other sites

An easier (and better designed) way of doing it is to do the following:

 

1. Instead of using <input> tags, use <button> tags.  This will make it easier for us to grab a hold of all the buttons within the form.

 

2. Use unobtrusive JavaScript.  There's no reason to embed JavaScript function calls within your HTML.  So, let's do things the right way.

 

<html>
   <head>
      <title>Calculator</title>
      <script type="text/javascript">
         window.onload = function()
         {
            var buttons = document.getElementsByTagName('button');

            for(var i = 0; i < buttons.length; i++)
            {
               buttons[i].onclick = function()
               {
                  alert(this.value + " was clicked.");
               }
            }
         }
      </script>
   </head>

   <body>

      <!-- someplace later, within your calculator form -->

      <button type="button" value="1">1</button><button type="button" value="2">2</button><button type="button" value="3">3</button>

      <!-- etc. -->

   </body>
</html>

Link to comment
Share on other sites

I think that what you need is something like this

<html>
<head>
<title>test</title>
<script type="text/javascript">
//using Nightslyr's function to assign the actions to the buttons
var calculation = "";

window.onload = function()
{
	var buttons = document.getElementsByTagName('input');

	for(var i = 0; i < buttons.length; i++)
	{
		if(buttons[i].type == "button"){
			buttons[i].onclick = function(){
				if(this.value == "="){
					//making a full statement
					var result = 0;
					calculation = "result = " + calculation + ";";
					//this next command will execute the text statement
					eval(calculation);
					//result should now contain the result of the statement
					alert(result);
					//reset calculation for new calculation
					calculation = "";
				}
				else{
					//adding the buttons value to the calculation string
					calculation += this.value
				}
			};
		}
	}
	calculation = "";
}
</script>


</head>
<body>
<input type='button' value = '0' />
<input type='button' value = '1' />
<input type='button' value = '2' />
<input type='button' value = '3' />
<input type='button' value = '4' />
<input type='button' value = '5' />
<input type='button' value = '6' />
<input type='button' value = '7' />
<input type='button' value = '8' />
<input type='button' value = '9' />
<input type='button' value = '+' />
<input type='button' value = '-' />
<input type='button' value = '/' />
<input type='button' value = '*' />
<input type='button' value = '=' />
</body>
</html>

 

code above creates a text line with the math calculation, and pressing = button will cause it to be calculated

Link to comment
Share on other sites

window.onload will trigger once the page is fully loaded, so not refresh

 

it's identical to the <body onload=''> tag

 

Exactly right.  window.onload is used when someone writes JavaScript in an unobtrusive manner to ensure all of the HTML document's elements are present in the DOM before the script attempts to access them.  That, in turn, gets rid of those pesky "something-or-another is not an object" errors that tend to crop up.

 

It's pretty much the same thing as using jQuery's $(document).ready(), except it isn't quite as fast.

Link to comment
Share on other sites

window.onload will trigger once the page is fully loaded, so not refresh

 

it's identical to the <body onload=''> tag

but your code shows that the function will only happen on window . onload

 

 

my func

<script>

function handleClick(id){

          element= document.getElementById(id);

          if(!element) element= document.getElementsById(id);

          if(element) {

              if(element.name) alert('You clicked ' + element.name);

              else if(element.id)  alert('You clicked somthign that dosent have a name but id of ' + element.id);

              //etc etc etc

          }

          else alert('could not find the element clicked');

}

<script>

<input type='button' id='button1' value='button1' onclick='handleClick('button1')' />

<input type='button' id='button2' value='button2' onclick='handleClick('button2')' />

<input type='button' id='button3' value='button3' onclick='handleClick('button3')' />

 

 

i think parts of your code are good where you reference the buttons as an array of all the buttons, its neat, but my code is more responisve, maybe they can be combined. My code can be used to handle a click of any HTML element, and it will respond straight away at any time without refresh or anything, in the function you can capture what was clicked and what to do with it.

Link to comment
Share on other sites

what the onload function does is assign the javascript function to each button, it's the same as putting the onclick='functionstuff("param");' in the htmlcode

so we wait till every button is loaded, then set the onclick event to every button, and done. a lot less type work, but your way works as well, only my way, it doesn't matter if more buttons are added, they will automatically have the same function assigned to them

Link to comment
Share on other sites

what the onload function does is assign the javascript function to each button, it's the same as putting the onclick='functionstuff("param");' in the htmlcode

so we wait till every button is loaded, then set the onclick event to every button, and done. a lot less type work, but your way works as well, only my way, it doesn't matter if more buttons are added, they will automatically have the same function assigned to them

 

ooooooooooooooooooooooooooooh sorry iwas being ignorant and dint read your code thorghly enogh, nice jerb.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.