#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    England
    Posts
    21
    Rep Power
    0

    Javascript - How to use getElementsByName?


    Hi

    Someone on these forums kindly gave me a piece of code that would calucate the values of a number of dymically created drop downs. Here it is:-

    function inst_timetaken()
    {
    var instTime = 0
    var selectBoxes = document.forms['form3'].getElementsByTagName ('select')
    for (var i = 0; i < selectBoxes.length; i++)
    {
    instTime += parseInt(selectBoxes[i].value)
    }

    now my drop downs are called inst_time1, inst_time2 etc.

    However I now have a problem as the code above works well when these are the only select boxes in the form. I now have to put some more select boxes within the same form.

    I thought about using getElementsByName but I couldn't get it do what the other code did, add the value of all the text boxes together at once and store it in a variable.

    Can any one help? (I'm new at javascript!) Many thanks!
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2003
    Posts
    1,014
    Rep Power
    15
    getElementsByName works on elements with exactly the same name. In your case they're different because of a counter.

    Here's a quick hack:
    Code:
    	for (var i = 0; i < selectBoxes.length; i++) {
    		if (selectBoxes[i].name.substring(0,9) == 'inst_time')
    			instTime += parseInt(selectBoxes[i].value)
    	}
    If your function is only called onchange (I don't know whether that is the case), you might consider changing the logic of the code.

    Hope this helps,
    Jeroen
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    England
    Posts
    21
    Rep Power
    0

    Thumbs up


    I think you provided the first bit of code Jeroen, once again your solution is brilliant!!!

    Many thanks!!!

    Cheers!

IMN logo majestic logo threadwatch logo seochat tools logo