CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   Button id passing value to javascript (http://www.codingforums.com/showthread.php?t=285549)

juliushg 01-10-2013 05:11 AM

Button id passing value to javascript
 
Is it possible to create a numeric id to asign to buttons (images) generated in a loop and pass that numeric id (the number part) to a function in javascript?

Something like this:

1st line:
Code:

<input id="q0" type="image" src="http://myurl/button-subtract.png" onclick="SubtractOne(0)"/> // (0) comes from q0
<input id="q0" type="image" src="http://myurl/button-subtract.png" onclick="AddOne(0)"/> // (0) comes from q0

2nd line:
Code:

<input id="q1" type="image" src="http://myurl/button-subtract.png" onclick="SubtractOne(1)"/> // (1) comes from q1
<input id="q1" type="image" src="http://myurl/button-subtract.png" onclick="AddOne(1)"/> // (1) comes from q1

And so on?

sbhmf 01-10-2013 07:45 AM

your code is illegal: two controls may not possess the same value for their id attribute, as all IDs must remain unique within the document.

if you must, use the name attribute to group controls, as it does not need to be unique.

what you want to do is certainly possible, but not necessary, as you may accomplish the same by passing 'this', as in '...onclick="SubtractOne(this)" ', where the entire tag itself is passed to the javascript function. the function may then retrieve the id from the object itself. Observe:

function SubtractOne(Caller){
alert( "the caller's id is " + Caller.getAttribute('id') );
}

juliushg 01-10-2013 10:30 AM

It worked. I only had to change all tags and passing the actual index to the function using this:

Code:

function AddOne(Caller){
var strCaller=Caller.getAttribute('id');
var callnumber=strCaller.replace("quantadd","");
++Quantity[callnumber];
document.getElementById(callnumber).innerHTML=Quantity[callnumber];
}
function SubtractOne(Caller){
var strCaller=Caller.getAttribute('id');
var callnumber=strCaller.replace("quantsubtract","");
--Quantity[callnumber];
document.getElementById(callnumber).innerHTML=Quantity[callnumber];
}

in the HTML loop (with ++listIndex):

Code:

<input id="quantsubtract" type="image" src="http://myurl/button-subtract.png" onclick="SubtractOne(this)">
<a id="tagtochange">0</a>
<input id="quantadd" type="image" src="http://myurl/button-add.png" onclick="AddOne(this)"/>

<script type="text/javascript">
document.getElementById("tagtochange").id=listIndex;
document.getElementById("quantadd").id="quantadd"+listIndex;
document.getElementById("quantsubtract").id="quantsubtract"+listIndex;
</script>

Now I have to use "callnumber" to get the position of the arrays. Thanks.


All times are GMT +1. The time now is 01:51 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.