Category Archives: JAVASCRIPT

(JS) Calculate price excluding VAT

Sometimes you need to calculate the price of a product excluding VAT, and the only details you have is the amount including vat and the vat percent. This might be a bit tricky in some applications when there are mixed VAT percentages.

For example, you payed 1000 space credits and in that sum there is a 12% VAT included. If you need to find out how much of the 1000 is actual VAT you can use this simple function:

function getAmountWithoutVat(amountIncludingVat, vatPercent) {

  var amountExVat = amountIncludingVat / (100 + vatPercent) * 100;
  var sumVat = amountIncludingVat - amountExVat;
  var amounts = {
        'priceExVat' : amountExVat.toFixed(2),
        'vat' : sumVat.toFixed(2)
      };

  return amounts;
}

console.log(getAmountWithoutVat(1000, 12));

Output:

{
  priceExVat: "892.86",
  vat: "107.14"
}

(JS) Validate date in format YYYY-MM-DD

A simple JS function to validate that a date string in the format YYYY-MM-DD is a valid date. Will validate that the day is correct for the given month, including leap years

/**
* Validate that a date string in the format YYYY-MM-DD is a valid date
* @param dateString (YYYY-MM-DD)
* @returns {boolean}
*/
function isValidDate(dateString) {

        // Date format: YYYY-MM-DD
        var datePattern = /^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;

        // Check if the date string format is a match
        var matchArray = dateString.match(datePattern);
        if (matchArray == null) {
            return false;
        }

        // Remove any non digit characters
        var cleanDateString = dateString.replace(/\D/g, ''); 

        // Parse integer values from date string
        var year = parseInt(cleanDateString.substr(0, 4));
        var month = parseInt(cleanDateString.substr(4, 2));
        var day = parseInt(cleanDateString.substr(6, 2));
      
        // Define number of days per month
        var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        // Adjust for leap years
        if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
            daysInMonth[1] = 29;
        }

        // check month and day range
        if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]) {
            return false;
        }

        // You made it through!
        return true;
    }

(JS) Validate Swedish personnummer and organisationsnummer

Javascript functions for validating Swedish personal identity numbers (personnummer), and organisation numbers (organisationsnummer). The functions for personal identity number will also validate co-ordination number (samordningsnummer).

  /**
     * Validate a 10 digit swedish personnummer
     * @param pnr
     * @returns {boolean|boolean}
     */
    function validatePersonnummer(pnr) {
        var personummer = cleanDigitString(pnr);
        if (personummer.length > 10) {
            return false;
        }

        return isValidLuhn(personummer) && isPersonnummerDate(personummer);
    }


    function validateOrganisationNumber(orgnr) {
        var orgnumber = cleanDigitString(orgnr);

        if (orgnumber.length < 10 || orgnumber.length > 12 || orgnumber.length == 11) {
            console.log(orgnumber.length);
        }

        return isValidLuhn(orgnumber);
    }


    /**
     * Remove any non digit characters
     * @param digitString
     * @returns {*}
     */
    function cleanDigitString(digitString) {
        return digitString.replace(/\D/g, '');
    }


    /**
     * Check if date is valid for personnummer
     * @param pnr
     * @returns {boolean}
     */
    function isPersonnummerDate(pnr) {
        var year = parseInt(pnr.substring(0, 2));
        var month = parseInt(pnr.substring(2, 4));
        var day = parseInt(pnr.substring(4, 6));

        // Check year and month values
        if (year < 0 || year > 99 || month < 0 || month > 12) {
            return false;
        }

        var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        // Adjust for leap years
        if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
            daysInMonth[1] = 29;
        }

        // Check that day is within range
        var dayIsValid = day > 0 && day <= daysInMonth[month - 1];

        // If day is outside range, check if it's +60 for samordningsnummer
        if (!dayIsValid) {
            dayIsValid = day > 60 && day <= daysInMonth[month - 1] + 60;
        }

        return dayIsValid;
    }

    /**
     * Check if last digit of number is vald Luhn control digit
     * @param pnr
     * @returns {boolean} 
     */
    function isValidLuhn(pnr) {
        var number;
        var checksum = 0;
        for (var i = pnr.length - 1; i >= 0; i--) {
            number = parseInt(pnr.charAt(i));
            if (i % 2 == 1) {
                checksum += number;
            } else {
                checksum += (number * 2) > 9 ? (number * 2) - 9 : number * 2;
            }
        }

        return checksum % 10 == 0;
    }

(JS) Newline to br

Replaces newline characters with <br> tags in the same style as the php nl2br function

// lewline to br - php style 
function nl2br (str, is_xhtml) {
        var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
        return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
    }

(JS) Super simple slider/carousel/slideshow

Here’s how you can make a super simple slideshow that changes slides on a timer interval. You could easily edit it so any other event, like a mouse click, will trigger the slide() function.

You can see it in action HERE

HTML

<div class="slider">

    <div class="slide red">
        <p>THIS IS SLIDE 1</p>
    </div>

    <div class="slide blue">
        <p>THIS IS SLIDE 2</p>
    </div>

    <div class="slide green">
        <p>THIS IS SLIDE 3</p>
    </div>

</div>

CSS

.slider {
    width: 500px;
    height: 300px;
    margin: 0 auto;

    /* DON'T CHANGE THESE */
    position: relative;
    overflow: hidden;
}

.slide {
    /* DON'T CHANGE THESE */
    position: absolute;
    width: 100%;
    height: 100%;
}

/** ONLY FOR STYLING THE EXAMPLE SLIDES */
.slide p {
    color: #FFF;
    text-align: center;
}

.red {
    background: red;
}

.blue {
    background: blue;
}

.green {
    background: green;
}

jQuery

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
    // Configurable values
    slider = $('.slider'); // Slider element
    slideDuration = 3000; // Duration of each slide in milliseconds
    slideSpeed = 1000; // Speed of slide animation in milliseconds (must be equal of less than slideDuration)


    width = slider.width();
    slider.children().hide().css({left: width});
    slider.children(':first').show().css({left: 0});

    // Slide in from the left
    $.fn.slideIn = function () {
        $(this).show().animate({
            left: "-=" + width
        }, slideSpeed / 2);
    }

    // Slide out to the left
    $.fn.slideOut = function () {
        $(this).animate({
            left: "-=" + width
        }, slideSpeed / 2, function () {
            $(this).hide().css({left: width});
        });
    }

    // Main slide function
    function slide() {
        currentSlide = slider.find('div:visible:first');
        nextSlide = (!slider.children(":last").is(":visible")) ? currentSlide.next() : slider.children(':first');

        currentSlide.slideOut();
        nextSlide.slideIn();
    }

    // Timer function
    window.setInterval(function () {
        slide();
    }, slideDuration);
</script>

And of course you could make this dynamic by spitting out the slides from a database… for example like this:

<div class="slider">

<?php foreach ($slides as $slide) { ?>

    <div class="slide">
        <p><?php $slide['content'] ?></p>
    </div>

<?php } ?>

</div>

Hide elements with radio buttons

Sometimes you want to show or hide certain elements of a form, depending on the selection of a radiobutton.

 

I am by no means any javascript ninja, but this is one simple way I came up with:

<html>
<head>
<script type="text/javascript">
	function DisplayElement(element)
	{
		x = element.value;
		if (x == 1) {
			document.getElementById('text').style.display = '';
		}
		else {
			document.getElementById('text').style.display = 'none';
		}
	}
</script>
</head>

<body>
<form name="form">
<input name="choice" type="radio" value="1" onclick="DisplayElement(this)" checked/>
<input name="choice" type="radio" value="2" onclick="DisplayElement(this)"/>
<input name="text" type="text" id="text"/>
</form>
</body>
</html>

 
This could apply to any element. For example, you could put a whole bunch of elements in a div and the hide/show the div. Like this:

<script type="text/javascript">
	function DisplayElement(element)
	{
		x = element.value;
		if (x == 1) {
			document.getElementById('container').style.display = '';
		}
		else {
			document.getElementById('container').style.display = 'none';
		}
	}
</script>

<form name="form">
<input name="choice" type="radio" value="1" onclick="DisplayElement(this)" checked/>
<input name="choice" type="radio" value="2" onclick="DisplayElement(this)"/>
<div id="container">
	<input type="checkbox"/>
	<input type="checkbox"/>
	<input type="text"/>
	<input type="text"/>
	<input type="text"/>
</div>
</form>

 
 
Here’s another way to do it. This example takes a number as a parameter instead of using the value of the element. A bit more compact code and it might be more flexible.

<script type="text/javascript">
    function DisplayElement(x)
    {
        if (x == 1) {
            document.getElementById('text').style.display = '';
        }
        else {
            document.getElementById('text').style.display = 'none';
        }
    }
</script>

<form name="form">
<input name="choice" type="radio" onclick="DisplayElement(1)" checked/>
<input name="choice" type="radio" onclick="DisplayElement(2)"/>
<input name="text" type="text" id="text"/>
</form>

 
And here’s an even more flexible version. In this example you can pass the id of the element you want to hide as a second argument to the function. This way you can use the same function to toggle the visibility of many different elements.

<script type="text/javascript">
    function DisplayElement(x,target)
    {
        if (x == 1) {
            document.getElementById(target).style.display = '';
        }
        else {
            document.getElementById(target).style.display = 'none';
        }
    }
</script>

<form name="form">
<input name="choice" type="radio" onclick="DisplayElement(1,'text')" checked/>
<input name="choice" type="radio" onclick="DisplayElement(2,'text')"/>
<input name="text" type="text" id="text"/>
</form>

Here is another post, to do the same thing with a checkbox.

Hide elements with checkbox

This is a slightly edited version of this post. Just to make it work with a checkbox instead of radio buttons.

 

 

<html>
<head>
<script type="text/javascript">	
	function DisplayElement(checked) 
	{
		if (checked) {
			document.getElementById('text').style.display = '';
		}
		else {
			document.getElementById('text').style.display = 'none';
		}
	}
</script>
</head>
<body>
<form name="form">
<input type="checkbox" onclick="DisplayElement(this.checked)" checked/>
<input type="text" id="text"/>
</form>
</body>
</html>