Validation for multiple select list box

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • asivakrupa
    New Member
    • Apr 2009
    • 14

    Validation for multiple select list box

    Hi,
    I am using a multiple select list box.

    I use an array to retrieve the values that are selected by the user.

    Code:
    <select name="competitor[]">
    When I try to validate the list box if the user does not select anything, I get errors. The error deals with the array declared.

    I am using PHP and the validation is done in Javascript. Please help out.

    Thanks in advance.
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function selectMultiple()
      {
    	var myArray="";
    		 try
    		  {
    		   for (var i=0; i<document.getElementById('mySelect').options.length; i++)
    		  { 
    					  if (document.getElementById('mySelect').options[i].selected == true) 
    					   { 
    						  //alert(document.getElementById('mySelect').options[i].text);
    			  myArray += document.getElementById('mySelect').options[i].text + ";";
    						} 
    		  }
    
    		   var resArray = myArray.split(";");
    		   if(resArray.length<=1) 
    			 alert("Please select the values in the list");
    		   else 
    			 alert("You have selected = "+(resArray.length-1));			 
    		 }
    		catch(e)
    		{
    		   alert(e.message);	
    		}
    
    }
    </script>
    </head>
    <body><form>
    <select name="mySelect" size="10" multiple>
      <option>Apple</option>
      <option>Pear</option>
      <option>Pea</option>
      <option>Banana</option>
      <option>Orange</option>
      <option>Mango</option>
      <option>Lime</option>
      <option>Goa</option>
      <option>Dates</option>
    </select>
    <input type="button" onclick="selectMultiple()" value="Select multiple">
    </form></body>
    </html>
    This is a validation for the multiple select box. As you were specifying array. I did this way. But i am not clear wether r u looking for this kind of validation or not.

    Regards
    Ramanan Kalirajan

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      I don't think that's what he meant and anyway, the code is incorrect because the select element has no ID.

      You can get the element by name:
      Code:
      document.forms[formname].elements["competitor[]"];
      then get its options and validate.

      Comment

      • dmjpro
        Top Contributor
        • Jan 2007
        • 2476

        #4
        @Acoder
        is "name[]" that a valid name?

        Comment

        Working...