Alessandro Lacava’s Blog

Google
 

January 16, 2007

How to detect the selected checkboxes using JavaScript

Filed under: Computer, JavaScript — alessandrolacava @ 6:31 pm

Here is an example of how you can retrieve the selected checkboxes using a JavaScript function:

HTML:
  1. function getSelectedValues(elem)
  2. {
  3. var elemNumber = document.myForm.test.length;
  4.  
  5. var selectedElems = [];
  6. for(j = 0; j <elemNumber; j++)
  7. {
  8. if(elem[j].checked)
  9. {
  10. selectedElems.push(elem[j].value);
  11. }
  12. }
  13. return selectedElems;
  14. }
  15. </script>
  16. </head>
  17.  
  18. <form id="myForm" name="myForm">
  19. <input type="checkbox" id="test" name="myCheckBox" value="test1">
  20. Test 1
  21.  
  22.  
  23. <input type="checkbox" id="test" name="myCheckBox" value="test2">
  24. Test 2
  25.  
  26.  
  27. <input type="button" value="Click Here" onclick="alert(getSelectedValues(document.myForm.myCheckBox));">
  28. </form>
  29. </body>
  30.  
  31. </html>

In the previous example when the user clicks on the button the selected checkboxes are displayed through an alert.


How to set a link as if the mouse were over it using JavaScript

Filed under: Computer, JavaScript, CSS — alessandrolacava @ 4:53 pm

In order to do it when, for example, the page loads, use the following JavaScript trick:

HTML:
  1.  
  2. <script type="text/javascript">
  3. function markAsOver(linkId)
  4. {
  5. var elem = document.getElementById(linkId);
  6. elem.focus();
  7. }
  8. </script>
  9. </head>
  10.  
  11. <body onload="javascript:markAsOver('myLink');">
  12. <a id="myLink" xhref="someUrl.htm">This is selected</a>
  13. </body>
  14.  
  15. </html>

Of course you can use the CSS to take advantage of the previous code and make the link look as if it were active (selected). Here is an example:

CSS:
  1. a:hover, a:active, a:focus
  2. {
  3. color: red;
  4. }

If you use this code as CSS then the myLink link will be red as soon as the page loads.

Note: The a:focus pseudo-class works with Firefox.