Skip to content

Logic for multiple and single select/combo boxes

Below is my code:

<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>

<script type="text/javascript">
var flag = false;
function test(selObject)

    var form = document.forms[0];

    var txtS =  form["city"];

    var len = txtS.length;

    for(var i=0; i<len; i++) 
        if (selObject == txtS[i] )
                alert("YOU ARE SELECTING MYSORE CITY");
                flag = true;
            if(!txtS[i].options[3].selected && flag)
                var result = confirm("Are you sure you wnat to travel to this city");
                    flag = false;
    }//end of for loop

<html:form action="/login">
    username:<input type="text" name="username" /></br>
    password:<input type="password" name="password"/></br>
    for(int i = 0; i < 10; i++){
        <html:select property="city" onchange="javascript:test(this);">
            <html:option value="B">BANGALORE</html:option>
            <html:option value="C">CHENNAI</html:option>
            <html:option value="M">MANGALORE</html:option>
            <html:option value="MR">MYSORE</html:option>
    <input type="submit" value="submit"/>

When select-box or combo-box is looped for ten times then I am getting form["city"] length as 10 properly and behaviour of alerts within combox-box is appropriate, but if I have a single-select-box, then instead of giving form["city"] length as 1 it gives it as 4 which is the number of option elements in my dropdown-box.

So my logic doesn’t work here.

How do I make it work for both single as well as multiple combo/select boxes.

Any help would be appreciated.



Please use a javascript library like jQuery for cross-browser compatibility.

You can use the following code to determine that only a single select element is present or multiple select elements with the same name are present:

if (selObject == txtS) {
    alert("Single select");
    // ... your logic for a single combo-box follows after this
} else {
    // your logic for multiple combo-box follows, like the "for" loop and if-else

When there is only one select box the line var txtS = form["city"]; will return an array of option elements within that select box and when more than one select box with the same name it returns an array of the select boxes.

Hope this helps.

Not related to your question, but this logic if(!txtS[i].options[3].selected && flag) will always return false.

User contributions licensed under: CC BY-SA
5 People found this is helpful