Validating multiple select boxes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • metafizzical
    New Member
    • Aug 2008
    • 4

    Validating multiple select boxes

    Hi,

    I'm currently trying to write a loop that can be used on several select boxes within the same form.

    Some sample HTML:
    [HTML]<!-- select box 1 -->
    <select name="qtyItsall greek" id="qtyItsallgr eek">
    <option value="0" selected="selec ted">0</option><option value="1">1</option>
    <option value="2">2</option><option value="3">3</option>
    </select>
    <!-- select box 2 -->
    <select name="qtyBluebe rrynights" id="qtyBlueberr ynights">
    <option value="0" selected="selec ted">0</option><option value="1">1</option>
    <option value="2">2</option><option value="3">3</option>
    </select>[/HTML]

    All form validation is done once the user hits a button that calls my main() function, which in turn calls a check_input function:

    Code:
    function check_input(element) {
        if (element.match(/^qty.*$/)) {
         var x = document.getElementById('orderform').qtyItsallgreek.selectedIndex;
         var y = document.getElementById.element.selectedIndex;
         return true;
    	}
    }
    function main() {
    	var myForm = document.getElementById('orderform');
            for (var i = 0; i < myForm.elements.length; i += 1) {
                var e = myForm.elements[i];
                if (e.type === "select-one") {
                    check_input(e.id);
                }
    }
    While var x contains the selectedIndex value, var y is interpreted literally, which gives the error that document.getEle mentById.elemen t.selectedIndex is undefined.

    Instead of referring to each specific select box like var x, is it possible to use the element variable in a similar way to var y?

    You might have noticed I'm quite new to JavaScript :-)

    PS. In the second code block on line 3, there shouldn't be a space within the word 'greek' - It's a non-breaking space that I can't get the message editor to remove :-)
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Since you're passing the ID, just pass the value to the getElementById method:
    [CODE=javascript]var y = document.getEle mentById(elemen t).selectedInde x;
    [/CODE]

    Comment

    • metafizzical
      New Member
      • Aug 2008
      • 4

      #3
      Thanks a lot. Seems obvious now. :-)

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        You're welcome. Post again back to the forum if you have more questions :)

        Comment

        Working...