How to delete an element from a comma separated string using Javascript


var value = 1,2,3,4,5;

var remove_val = '3';

var separator = ",";

var new_value = value.split(separator);

for(var i = 0 ; i < new_value.length ; i++) {

if(new_value[i] == remove_val) {

new_value.splice(i, 1);

return new_value.join(separator);

}

}

Advertisements

Using PHP Array in Javascript

If you have a PHP Array and want to perform some javascript operations by looping the PHP Array, then I recommend you to use PHP foreach loop instead of Javascript forEach loop.


function myfunction() {

<?php foreach($myArray as $val) { ?>

console.log('<?=$val;?>');

<?php } ?>

}

 

Print div using Javascript

Here is a full code to print contents of a div using javascript. Just create a div and give any id to it and then create an anchor tag as given below :


<a href="javascript:void(0);" onclick="printdiv('IDOFDIV')">Print</a>

After creating this anchor tag put the below javascript code in your page.


function printdiv(printpage) {

var newstr = document.getElementById(printpage).innerHTML;

var oldstr = document.body.innerHTML;

document.body.innerHTML =newstr;

window.print();

document.body.innerHTML = oldstr;

return false;

}

Countdown timer using Javascript

Here is the full javascript tutorial for creating a countdown timer to a certain date. This count down timer contains days, hours, minutes and seconds as well.


// Set the date to which the timer continues

var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();

var x = setInterval(function() {

// Todays date and time

var now = new Date().getTime();

// Distance between now and the countdown date

var distance = countDownDate - now;

var days = Math.floor(distance / (1000 * 60 * 60 * 24));

var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));

var seconds = Math.floor((distance % (1000 * 60)) / 1000);

// Putting the countdown timer in element with ID demo

document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

// If countdown is over, then putting the text in element with ID demo

if (distance < 0) {

clearInterval(x);

document.getElementById("demo").innerHTML = "EXPIRED";

}

}, 1000);

One more thing to do, just place the below code in your body :


<p id="demo"></p>