Click here to Skip to main content
15,900,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do you make an attribute equal a return value of a javascript method?


HTML
<script language="javascript">
function getValue(divbox){
var returnvalue = 0;
for(var i = 0 ;i < divbox.chilNodes.length;i++)
{
returnvalue += +divbox.childNodes[i].getAttribute("num");
}
alert(returnvalue);
return returnvalue;
}
</script>

<style>


</style>

<div id="id1" v="getValue(this);">
<p num="2" ></p>
<p num="3" ></p>
<p num="2" ></p>
<p num="2" ></p>
<p num="2" ></p>
<p num="4" ></p>
</div>

<button  önclick="alert(getElementById('id1').getAttribute('v'))">Get Sum</button>



So basically I want to make id1.v equal the sum of all the num attributes.

So when I use getAttribute("v") I want it to return the sum of all the nums


Here is an example in C#.

C#
int Value
{
    get { return getNum(); }
}

public int getNum()
{
    return new Random().Next(0, 1000);
}
Posted
Updated 30-May-12 11:43am
v3
Comments
ZaiDz 30-May-12 2:27am    
When I push the button it shows "getValue(this);" but I want it to run that method and return the string instead
Sunasara Imdadhusen 31-May-12 1:14am    
Not clear!!!

1 solution

Hi
Use following code

Javascript
C#
function getValue(obj){
  var divbox = document.getElementById(obj);
  var returnvalue=0; 
  for(var i = 0 ;i < divbox.chilNodes.length;i++)
  {
     returnvalue += Number(divbox.childNodes[i].getAttribute("num"));
  }
  getElementById('id1').setAttribute('v',returnvalue);
}

HTML
HTML
<body  önload="getValue('id1');">
<div id="id1" v="">
<p num="2"></p>
<p num="3"></p>
<p num="2"></p>
<p num="2"></p>
<p num="2"></p>
<p num="4"></p>
<button  önclick="alert(document.getElementById('id1').getAttribute('v'))">Get Sum</button>
</div></body>


Thanks,
Imdadhusen
 
Share this answer
 
v3
Comments
ZaiDz 30-May-12 17:37pm    
Thanks for answering but that's not what I need
ZaiDz 30-May-12 17:54pm    
I updated the question with an example in C#

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900