You are here: Re: Anyone know why this javascript doesn't work? « HTML « IT news, forums, messages
Re: Anyone know why this javascript doesn't work?

Posted by Michael Winter on 12/16/05 20:44

On 16/12/2005 18:27, Ed Jay wrote:

[snip]

> function get_menu_value(menu_name) {
>
> var mValue = 0;
>
> for(var i=0; i < menu_name.length; i++) {

Why does the length of the name determine the number of iterations of
this loop?

> if (document.form1.elements[menu_name+(i)].checked) {

The expression in the square brackets will be evaluated, converted to a
string, and used as a property name. In your example, these names will
be 'choice0', 'choice1', ..., 'choice5'. Not only are there only five
checkboxes (you create six names), none of these names match a control
within the form, resulting in an undefined value, and an error with the
subsequent property access.

> mValue = mValue + document.form1.elements[menu_name+(i)].value;

The value property is a string. The addition operator, with a string and
a number operand, will perform a concatenation. I suspect that you want
arithmetic addition.

[snip]

> return false;

[snip]

> <input type = "submit" onclick="get_menu_value('choice')">

As you do not return the value returned by the get_menu_value function,
it will have no effect. In any case, it is generally better to use the
submit event of the form, passing a reference to the form, rather than
the click event of the button.

function getMenuValue(menuName, form) {
var value = 0,
menu = form.elements[menuName];

for(var i = 0, n = menu.length; i < n; ++i) {
if(menu[i].checked) {
/* Unary plus performs explicit conversion to Number. */
value += +menu[i].value;
}
}
alert(value);

return false;
}

<form action="..." onsubmit="return getMenuValue('choice', this);">
<!-- ... -->
</form>

Hope that helps,
Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация