JavaScript

How to format a decimal number in JavaScript

In JavaScript you can use a built-in method to format a decimal number so that it is displayed using, at most, x decimal places. Here is an example: var num = 3.1356; var x = 3; alert(num.toFixed(x)); // displays 3.136 As you may have guessed the method is toFixed. It accepts one parameter which is the number of decimal places to take into account. Note: The number gets rounded as you can notice by the example above.

How to display an element to the center of the browser

Sometimes you might need to display an element, for example a div, to the center of the browser. Here is an example of how you can do it using JavaScript and CSS. function init() { // Reference to the element var loading = document.getElementById("loading"); // The div's width, set within the CSS class var loadingWidth = loading.offsetWidth; // The div's width, set within the CSS class var loadingHeight = loading.offsetHeight; // The browser's body's width var documentWidth = document.

How to detect the selected checkboxes using JavaScript

Here is an example of how you can retrieve the selected checkboxes using a JavaScript function: <html> <head> <script> function getSelectedValues(elem) { var elemNumber = document.myForm.test.length; var selectedElems = []; for(j = 0; j < elemNumber; j++) { if(elem[j].checked) { selectedElems.push(elem[j].value); } } return selectedElems; } </script> </head> <body> <form id="myForm" name="myForm"> <input type="checkbox" id="test" name="myCheckBox" value="test1"> Test 1 <input type="checkbox" id="test" name="myCheckBox" value="test2"> Test 2 <input type="button" value="Click Here" onclick="alert(getSelectedValues(document.