Recent Posts

JavaScript listbox validation

Saturday 23 May 2015


Validate JavaScript listbox selected value: To get & validate JavaScript listbox selectedindex value, we have added listbox selectedindex example below. Here you have to use options[x].selected property to find each element from list as to be selected or not using for loop. Run the for loop on each elements and search each element position from list, if its selected it will return true if not will return false, remember JavaScript returns true automatically , if you have not considered then let it be , it won’t produces any error . Anyway, please look at the example below –

Validate listbox in JavaScript Example:

<script> function validateListBox() { var ListBoxObject=document.getElementById("fruits") var tot=0;
for (var i = 0;i < ListBoxObject.length; i++) { if (ListBoxObject.options[i].selected == false) {tot=tot+1;} }
if (ListBoxObject.length==tot)   
   {alert('Please select fruits from a list')
    return false;
  
}
 } function DeselectListBox() { var ListBoxObject=document.getElementById("fruits") for (var i = 0;i < ListBoxObject.length; i++) { if (ListBoxObject.options[i].selected ) { ListBoxObject.options[i].selected = false //deselect all JavaScript values assign false property to list values } } } </script> <select name="fruits" id="fruits" multiple> <option value="Apple">Apple</option> <option value="Apricot">Apricot</option> <option value="Asparagus">Asparagus</option> <option value="Fig">Fig</option> <option value="Avocado">Avocado</option> <option value="Banana">Banana</option> <option value="Clementine">Clementine</option> <option value="Honeydew melon">Honeydew melon</option> </select> <button onclick="javascript:validateListBox();">Validate List Box</button> <button onclick="javascript:DeselectListBox();">Deselect List Box</button>

Implementation : Try it...

No comments:

Post a Comment

 

Blogger JavaScript

Contact Us

Name

Email *

Message *

Tutorials