Posts

Showing posts from April, 2017

jQuery: Select an element by name

Image
Although the title says jQuery  in it, I will also provide Javascript solution for this snippet. Live Demo at CodePen Suppose we have the following checkbox input: <input type="checkbox" name="colors" value="red" /> Red <input type="checkbox" name="colors" value="green" /> Green <input type="checkbox" name="colors" value="blue" /> Blue in jQuery: var colors = $('[name="colors"]'); // non-element specific var colors = $('input[name="colors"]'); // specific to "input" elements only in JavaScript: // returns array of elements with name="colors" var colors = document.getElementsByName('colors'); var colors = document.querySelectorAll('[name="colors"]'); // returns first element with name="colors" var colors = document.getElementsByName('colors')[0]; var colors = documen...

Pass Values from PHP to Javascript

Image
There are many ways to pass PHP variables to Javascript but I will only cover 3 most common: 1. Echo the data. 2. Use a hidden field or element. 3. Use a data attribute 1. Echo the data. The first one which is the simplest can be done as follows: var data = <?php echo $data;  ?>; But the above code can cause an issue depending on the data type and it's value, so we use json_encode to convert the data. In PHP: $name = "John O'Reily";     // a string with single quote $age = 14;                           // an integer number $address = array(                // an array     'street' => '123 Street',     'city' => 'XYZ City' ); In Javascript: var name = <?php echo json_encode($name);  ?>; var age = parseInt(<?php echo json_encode($age);  ?>); var address = <?php echo json_encode($address);  ?...

Javascript: Creating a dynamic Copyright footer

Image
Updating your website's copyright year on annual basis can be annoying, to make your copyright year dynamically change, simply use the new Date.getFullYear(); code as shown in the example below. Live Demo  at CodePen the HTML: &copy; 1997 - <span id="currentYear"></span> // desired ouput: © 1997 - 2017 on pure Javascript: document.getElementById('currentYear').innerHTML = new Date().getFullYear(); or if you use jQuery [ CodePen demo ]: $('#currentYear').html(new Date().getFullYear());