Friday, November 24, 2023

Multi Upload Vanilla JS and PHP

1. Form Input Data:

---------------------

<!DOCTYPE html>

<html lang="en">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> Multi Upload Vanilla Javascript </title>

    <script>

        function uploadFiles() {

            var formdata = new FormData();

            var file = document.getElementsByName("filegroup")[0].files;

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

                formdata.append("data"+i, file[i]);

            }

                var ajax = new XMLHttpRequest();

                ajax.open("POST", "upload.php");

                ajax.onreadystatechange = function () {

                    if (ajax.readyState == 4 && ajax.status == 200) {

                        var resp = ajax.responseText;

                        console.log(resp);

                    }

                }

                ajax.send(formdata);

        }



    </script>

</head>


<body>


    <form method="post" enctype="multipart/form-data">

        <input type="file" name="filegroup" multiple />

        <input type="button" value="Upload" onclick="uploadFiles()" />

    </form>



</body>


</html>


-----------------------

2. Upload Proses 

-----------------------

<?php


$file = $_FILES;

$jumlah = count($file);

$list_file = array();

for($i=0; $i<$jumlah;$i++){

    $list_file[] = $file['data'.$i]['name'];

    move_uploaded_file($file['data'.$i]['tmp_name'], "upload/".$file['data'.$i]['name']);

    //bisa lansung di input ke DB di dalam Looping ini

}

echo json_encode($list_file);

?>

Sunday, October 29, 2023

Event Calendar Vanilla Javascript

        const numDays = (y, m) => new Date(y, m, 0).getDate();

        console.log(numDays(2023, 10));


        let dayone = new Date(2023, 9, 1).getDay();

        console.log(dayone+" hari pertama di bulan ini 0 untuk minggu");


        // get the last date of the month

        let lastdate = new Date(2023, 9 + 1, 0).getDate();

        console.log(lastdate+" tanggal terakhir bulan ini");


        // get the day of the last date of the month

        let dayend = new Date(2023, 9, lastdate).getDay();

        console.log(dayend+" nama hari terakhir selasa di bulan ini");


        // get the last date of the previous month

        let monthlastdate = new Date(2023, 9, 0).getDate();

        console.log(monthlastdate+" tanggal terakhir dari bulan sebelumnya");

Wednesday, October 25, 2023

Text Editor Javascript

 html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Simple Text Editor</title>
        <link rel="stylesheet" href="./style.css" />
    </head>
    <body>
        <div>
            <p><button id="open" onclick="openFile()"> to open a file </button> | <button id="save" onclick="saveFile()" style="display:none"> to save a file </button></p>
        </div>
        <br />
        <textarea name="" id="editor" cols="80" rows="10"></textarea>

        <script src="./index.js"></script>
    </body>
</html>
 

 

Javascript

let fileHandle
const textarea = document.querySelector("textarea")

async function openFile() {
    const [handle] = await window.showOpenFilePicker()
    fileHandle = handle
    const file = await handle.getFile()
    const text = await file.text()
    textarea.value = text
    document.getElementById("save").style = 'display:block';
}

async function saveFile() {
    const writable = await fileHandle.createWritable()
    await writable.write(textarea.value)
    await writable.close()
}
 

 

 

Thursday, September 28, 2023

Encrypt Decrypt PHP OPEN SSL PHP

 <?php
 
$simple_string = "Welcome to Jungles\n";
 
echo " Text Asli : " . $simple_string;
 
$ciphering = "AES-128-CTR";
 
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
 
$encryption_iv = '1234567891011121';
 
$encryption_key = "Test!234";
 
$encryption = openssl_encrypt($simple_string, $ciphering,
            $encryption_key, $options, $encryption_iv);
 
echo " 1. Encrypted String: " . $encryption . "\n";
 
$decryption_iv = '1234567891011121';
 
$decryption_key = "Test!234";
 
$decryption=openssl_decrypt ($encryption, $ciphering,
        $decryption_key, $options, $decryption_iv);
 
echo " 2. Decrypted String: " . $decryption;
 
?>

Sunday, September 17, 2023

Edit Online HTML Javascript

 1.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> Custom File manager</title>

</head>

<body>

    <p><button onclick="openFile()"> Open File </button></p>

    <p><textarea id="code" cols="55" rows="15" contenteditable="true"></textarea></p>

    <p><button onclick="save()"> Save </button></p>

</body>

<script src="main.js"></script>

</html>


2. javascript

let handler;

async function openFile(){

    let [handler] = await window.showOpenFilePicker();

    let getfiles = await handler.getFile();

    let gettext = await getfiles.text();

    let textarea = document.getElementById("code");

    textarea.innerHTML = gettext;   

}


async function save(){

    const newhandler = await window.showSaveFilePicker();

    let stream = await newhandler.createWritable();

    let textarea = document.getElementById("code").value;

    await stream.write(textarea);

    await stream.close();

}

Monday, September 4, 2023

Add Date / Month / with difference Years

 <script>

Date.isLeapYear = function (year) {
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () {
    return Date.isLeapYear(this.getFullYear());
};

Date.prototype.getDaysInMonth = function () {
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};

var myDate = new Date("11/31/2012");
var result = myDate.addMonths(3);



console.log(myDate);
</script>

Thursday, August 31, 2023

JSON Link Data

 <script type="application/ld+json">
    {
      "@context": "https://schema.org/",
      "@type": "Recipe",
      "name": "Party Coffee Cake",
      "author": {
        "@type": "Person",
        "name": "Mary Stone"
      },
      "datePublished": "2018-03-10",
      "description": "This coffee cake is awesome and perfect for parties.",
      "prepTime": "PT20M"
    }
    </script>

Saturday, August 26, 2023

Reverse Number Vanilla Javascript

function reversedNum(num) {

  return (

    parseFloat(

      num

        .toString()

        .split('')

        .reverse()

        .join('')

    ) * Math.sign(num)

  )                 

}

console.log(reversedNum(num)) 

Saturday, August 19, 2023

POST CSRF TOKEN LARAVEL DENGAN VANILLA JS

 1 . tambahkan csrf token di main layout atau master layout seperti berikut :

             <meta name="csrf-token" content="{{ csrf_token() }}" />

2. Di terapkan di page apapun untuk vanilla jacscript , seperti berikut

function sample(e){

var ajax = new XMLHttpRequest();

ajax.open("POST", e.dataset.url, true);

ajax.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content); // disini

ajax.onreadystatechange = function () {

if (ajax.readyState == 4 && ajax.status == 200) {

if(ajax.responseText.status){

    window.location.reload();

}else{

        console.log(ajax.responseText);

}

}

}

ajax.send();

}

 

Tuesday, August 15, 2023

Add Remove Textbox Jquery Javascript

 <!doctype html>
<html lang="en">

<head>
  <title>Add or Remove Input Fields Dynamically</title>
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  </script>
  <style>
    body {
      display: flex;
      flex-direction: column;
      margin-top: 1%;
      justify-content: center;
      align-items: center;
    }

    #rowAdder {
      margin-left: 17px;
    }
  </style>
</head>

<body>
  <h2 style="color:green">GeeksforGeeks</h2>
  <strong> Adding and Deleting Input fields Dynamically</strong>
  <div style="width:40%;">
    <form>
      <div class="">
        <div class="col-lg-12">
          <div id="row">
            <div class="input-group m-3">
              <div class="input-group-prepend">
                <button class="btn btn-danger" id="DeleteRow" type="button">
                  <i class="bi bi-trash"></i>
                  Delete
                </button>
              </div>
              <input type="text" class="form-control m-input">
            </div>
          </div>

          <div id="newinput"></div>
          <button id="rowAdder" type="button" class="btn btn-dark">
            <span class="bi bi-plus-square-dotted">
            </span> ADD
          </button>
        </div>
      </div>
    </form>
  </div>
  <script type="text/javascript">
    $("#rowAdder").click(function () {
      newRowAdd =
        '<div id="row"> <div class="input-group m-3">' +
        '<div class="input-group-prepend">' +
        '<button class="btn btn-danger" id="DeleteRow" type="button">' +
        '<i class="bi bi-trash"></i> Delete</button> </div>' +
        '<input type="text" class="form-control m-input"> </div> </div>';

      $('#newinput').append(newRowAdd);
    });
    $("body").on("click", "#DeleteRow", function () {
      $(this).parents("#row").remove();
    })
  </script>
</body>

</html>

ENV PHP

  

 RULE OF ENV FILE PHP

  1. composer require vlucas/phpdotenv

  2. Create ".env" file

  3. require_once('./vendor/autoload.php');
  4. use Dotenv\Dotenv; 

  5. $dotenv = Dotenv::createImmutable(__DIR__);

  6. $dotenv->load();
  7. $_ENV['CALL_FROM_ENV_FILE']   
 
  

 

Sunday, August 13, 2023

PUT , PATCH LARAVEL BLADE

 

<form action="{{ route('route_name') }}" method="post">
    {{ method_field('PUT') }}
    {{ csrf_field() }}
</form>

Monday, August 7, 2023

EyeDrop Javascript

 <button id="start-button">Open the eyedropper</button> <span id="result"></span>
<script>
document.getElementById("start-button").addEventListener("click", () => {
  const resultElement = document.getElementById("result");

  if (!window.EyeDropper) {
    resultElement.textContent =
      "Your browser does not support the EyeDropper API";
    return;
  }

  const eyeDropper = new EyeDropper();

  eyeDropper
    .open()
    .then((result) => {
      resultElement.textContent = result.sRGBHex;
      resultElement.style.backgroundColor = result.sRGBHex;
    })
    .catch((e) => {
      resultElement.textContent = e;
    });
});
</script>

Sunday, August 6, 2023

Load Image Canvas and Printed Vanilla Js

 


<script src="https://printjs-4de6.kxcdn.com/print.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://printjs-4de6.kxcdn.com/print.min.css">

<canvas id="card_canvas"></canvas>

<hr>

<button onclick="print()">Print</button>

<script>

function print(){

const cv = document.getElementById("card_canvas");

const url = cv.toDataURL("image/jpeg");

            printJS({printable: url, type: 'image', base64: true, imageStyle: 'width:100%;height:100%;'});

}

    function updateCanvas(){


        var canv = document.getElementById('card_canvas');

        var context = canv.getContext('2d');

        canv.width = window.innerWidth;

        canv.height = 930;

        var image = new Image();

        image.src = 'sertifikat.jpeg';

        image.addEventListener("load", function () {

            context.drawImage(image, 0, 0, window.innerWidth, 930);

            context.font = "bold 45px Calibri";

            context.fillStyle = "Red";

            context.fillText("rifqi", 480, 390);

        });


    }

    window.addEventListener("load",updateCanvas)

</script>


Saturday, August 5, 2023

Class Static dan Compact PHP

 <?php

class database {

  public static function user($array) {

    array_walk($array, function($name){

        echo "Hello + ".$name ."<br>";

    });

  }

}

$array = array("Muhammad","Rifqi");

$row = database::user($array);

echo"<pre>";

print_r($row);

?>

-----------------------------------------------------------------------------------------------

<?php

$city  = array("San Francisco","aaaa","bbb");

$state = array("San Francisco","aaaa","bbb");

$event = array("San Francisco","aaaa","bbb");

$location_vars = array("city", "state",'event');

$res = compact($location_vars);

echo "<pre>";

print_r($res);

?>


Lambda dan Clousure serta callback

<?php

//contoh lambda

$call = function($say){

    return "HAllo + ".$say;

};

echo $call('rifki');

?>


<hr>


<?php

//contoh clousur

$name = " rifki";

$hello = function() use ($name) {

    echo "HAllo + ".$name;

};

$hello();

?>


<hr>


<?php

//clousue dengan callback

$user = array("muhammad","rifki");

array_walk($user, function($name){

    echo "HAllo + ".$name ."<br>";

});


?>






 

Thursday, August 3, 2023

Read QrCode Javascript

 <html>
<head>
    <title>SCAN QR</title>
    <script>
        function scanqr() {
            var file = document.getElementById("file").files[0];
            var formdata = new FormData();
            formdata.append("file", file);
            var hr = new XMLHttpRequest();
            hr.open("POST", 'http://api.qrserver.com/v1/read-qr-code/');
            // hr.setRequestHeader("Content-Type", "application/json");
            // hr.setRequestHeader("Content-Type", "multipart/form-data");
            hr.onreadystatechange = function() {
                if (hr.readyState == 4 && hr.status == 200) {
                    var return_data = JSON.parse(hr.responseText);
                        document.getElementById("status").innerHTML = JSON.stringify(return_data);
                }
            }
            hr.send(formdata);
            document.getElementById("status").innerHTML = "processing...";
        }

        function scanqr2(){

            var file = document.getElementById("file").files[0];
            var formdata = new FormData();
            formdata.append("file", file);
            fetch('http://api.qrserver.com/v1/read-qr-code/', {
                method : 'POST',
                body : formdata
            })
            .then(res => res.json())
            .then((data) => {
                console.log(data)
            })
        }

        // Using Jpg/jpeg to output better
    </script>
</head>
<body>
    <form enctype="multipart/form-data" action="#">
        <p align="center"><input type="file" id="file" onchange="scanqr()"></p>
        <p align="center"><div id="status"></div></p>
    </form>
</body>
</html>

Sunday, July 30, 2023

Qrcode Scanner Javascript

 <!DOCTYPE html>

<html>

<head>

    <title>Qr Code Scanner</title>

    <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js" type="text/javascript"></script>

</head>

<body>

    <div id="reader" width="600px"></div><br>

    <div id="result" width="600px"></div>

</body>

<script>

    // console.log(Html5QrcodeScanner);

    let html5QrcodeScanner = new Html5QrcodeScanner(

        "reader",

        { fps: 10, qrbox: { width: 250, height: 250 } },

  /* verbose= */ false);

    html5QrcodeScanner.render(onScanSuccess, onScanFailure);


    function onScanSuccess(result){

        document.getElementById("result").innerHTML=result;

        html5QrcodeScanner.clear();

        document.getElementById("reader").remove();

    }


    function onScanFailure(error){

        document.getElementById("result").innerHTML=error;

    }

</script>

</html>

Aplikasi Adzan Online

 <p id="now"></p>

<p id="set"></p>

<p id="success"></p>

<script>

    function now() {

        const date = new Date();

        const d = date.getDate();

        const m = date.getMonth();

        const y = date.getFullYear();

        const h = date.getHours();

        const mn = date.getMinutes();

        const s = date.getSeconds();

        const nd = new Date(Date.UTC(y, m, d, h, mn, s));

        return nd.toLocaleString('id-ID', { timeZone: 'UTC' });

    }



    function setTime() {


        const date = new Date('August 19, 1975 23:15:30');;

        const d = date.setDate(30);

        const m = date.setMonth(6);

        const y = date.setFullYear(2023);

        const h = date.setHours(15);

        const mn = date.setMinutes(8);

        const s = date.setSeconds(1);

        const nd = new Date(Date.UTC(date.getFullYear(y), date.getMonth(m), date.getDate(d), date.getHours(h), date.getMinutes(mn), date.getSeconds(s)));

        return nd.toLocaleString('id-ID', { timeZone: 'UTC' });

    }


    window.addEventListener("load", () => {

        var text = "";

        document.getElementById("set").innerText = setTime();

        setInterval(function () {

            document.getElementById("now").innerText = now();

            if (now() >= setTime()) { 

                text = "OKE BRO";

                document.getElementById("success").innerHTML = text  

                //disesuaikan dengan suara yang di inginkan         

            }else{

                text = "GAGAL BRO";

                document.getElementById("success").innerHTML = text 

            }

        }, 500);


        if (!navigator.getAutoplayPolicy) {

            console.log("navigator.getAutoplayPolicy() not supported.");

        } else {

            console.log("navigator.getAutoplayPolicy() is supported.");

        }


    })


</script>

Saturday, July 29, 2023

Qrcode Vanilla Javascript

 <html>

<head>

    <title>

        QRCODE

    </title>

    <style>

        input,

        button,

        img {

            padding: 10px;

        }

    </style>

</head>

<body>

    <p><img id="qrcodeimg"></p>

    <p><input type="text" id="text" placeholder="entri text"></p>

    <p><button id="generate">GENERATE</button></p>

    <p><button id="download">DOWNLOAD</button></p>

</body>

<script>

    const img = document.querySelector("#qrcodeimg");

    const text = document.querySelector("#text");

    const generate = document.querySelector("#generate");

    const download = document.querySelector("#download");

    generate.addEventListener("click",(e)=>{

            const qr = `https://api.qrserver.com/v1/create-qr-code/?data=${text.value}&amp;size=100x100`;

            img.setAttribute('src',qr);

            img.setAttribute('alt','qrcode-vanilla-js');

            img.setAttribute('width', 100)

    })

    download.addEventListener("click", async (e) => {

            const data = img.getAttribute('src');

            const get = await fetch(data);

            const blob = await get.blob();

            const downloadLink = document.createElement("a");

            downloadLink.href = URL.createObjectURL(blob);

            downloadLink.download = 'qr.jpg';

            downloadLink.click();

    })

</script>

</html>

Geolocation Vanilla Javascript

<html>

<head>

    <title>

        GEO

    </title>

</head>

<body>

    <button>GET LOCATION</button>

</body>

<script>

    const button = document.querySelector("button");

    button.addEventListener("click", (e) => {

        navigator.geolocation.getCurrentPosition(position => {

            const { latitude, longitude } = position.coords;

            console.log(`https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${latitude}&lon=${longitude}`)

            const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${latitude}&lon=${longitude}`;

            fetch(url)

            .then(response => response.json())

            .then((data) => { console.log(data) })

            .catch((error) => {console.log(error)});

        })

    })

</script>

</html> 

Simple Drag and Drop Javascript

 <html>


<head>

    <title>

        DND

    </title>

    <style>

        .div {

            background-color: black;

            width: 100px;

            height: 100px;

            position: absolute;

            color: bisque;

            cursor: move;

            left: 35%;

            top: 10%;

        }

    </style>

</head>


<body>


    <div class="div">

        HALLLOW

    </div>


</body>

<script>


    const div = document.querySelector("div");

    let offsetX, offsetY;


    const move = (e) => {

        console.log("move:",e.clientX - offsetX)

        div.style.left = `${e.clientX - offsetX}px`;

        div.style.top = `${e.clientY - offsetY}px`;

    }


    div.addEventListener("mousedown", (e) => {

        console.log("mousedown:",e.clientX, div.offsetLeft)

        offsetX = e.clientX - div.offsetLeft;

        offsetY = e.clientY - div.offsetTop;

        document.addEventListener("mousemove", move);

    })


    document.addEventListener("mouseup", () => {

        document.removeEventListener("mousemove", move);

    })


</script>


</html>

List Sample Api

 Map : https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=-34.44076&lon=-58.70521

   {lat}/{long}

Qrcode :

        : <img src="https://api.qrserver.com/v1/create-qr-code/?data=HelloWorld&amp;size=100x100" alt="" title="" />

Quote api

        : http://api.quotable.io/random

Translate : 

        https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id

Friday, July 28, 2023

Copy Paste Image Javascript

 <script>

    window.addEventListener("paste",(event)=>{

        const aaa = event.clipboardData.files;

        if(aaa.length > 0){

            const img = URL.createObjectURL(aaa[0]);

                document.body.innerHTML = `<img src="${img}"" width="200">`;

        }

    })

</script>

Saturday, June 24, 2023

Get Value Multi Combo Box Vanilla Js


<select multiple id="test" style="width: 100px;">

    <option value="1">1</option>

    <option value="2">2</option>

    <option value="3">3</option>

</select>



<script>

const multi = document.getElementById("test");

multi.addEventListener("change",(e)=>{

    const arr = [];

    for(var i = 0; i < e.target.selectedOptions.length; i++){

            console.log(e.target.selectedOptions[i].value);

    }

});

</script> 

Saturday, June 3, 2023

Count Duplicate String Javascript

 const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];

const counts = arr.reduce((acc, value) => ({
   ...acc,
   [value]: (acc[value] || 0) + 1
}), {});

console.log(counts);

Tuesday, May 16, 2023

Captcha PHP

 <?php

session_start();

$code=rand(1000,9999);

$_SESSION["code"]=$code;

$im = imagecreatetruecolor(50, 24);

$bg = imagecolorallocate($im, 22, 86, 165); //background color blue

$fg = imagecolorallocate($im, 255, 255, 255);//text color white

imagefill($im, 0, 0, $bg);

imagestring($im, 5, 5, 5,  $code, $fg);

header("Cache-Control: no-cache, must-revalidate");

header('Content-type: image/png');

imagepng($im);

imagedestroy($im);

?>


Encrypt & Decript PHP

<?php

function encrypt( $q ) {

$cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';

$qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );

return( $qEncoded );

}

function decrypt( $q ) {

$cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';

$qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");

return( $qDecoded );

}

?>

----------------------------------------------------------------------------------------------------------------------------

<?php

 $id = "USR13";

$Encrypted = encrypt($id);

$Decrypted = decrypt($Encrypted);

?>

<a href="index.php?id=<?php echo $Encrypted?>">Enkrip</a>

<a href="index.php?id=<?php echo $Decrypted?>">Dekript</a>

?>


Sunday, May 14, 2023

Cek Posisi Mouse Di Browser Dengan Vanilla Javascript

1. Cek Posisi Mouse

var y = window.pageYOffset;

var x = window.pageXOffset;

window.addEventListener("click", (e) => {

    console.log(`mouse location = X: ${e.x}, Y: ${e.y}`)

  }) 

2. Set Default Offset Page

  function up() {

    window.pageYOffset = 0;

  }



Beberapa CaraSum Array Vanilla Javascript

 1. Cara Pertama

    const arr = [1, 2, 3, 4];

    sum = arr.reduce((a, b) => a + b, 0);

    console.log(sum)

2. Cara Kedua

var arr = [1, 2, 3, 4];

var total = 0;

for (var i in arr) {
  
      total += arr[i];

}

console.log(total)

Mencari Index dalam sebuah array vanilla javascript dan menjumlahkan sisi kiri dan sisi kanan array

1. Menjumlahkan array sisi kanan dan sisi kiri dari sebuah index

function findEvenIndex(arr)

{

  for(let i = 0; i < arr.length; i++) {

    let leftTotal = arr.slice(0, i).reduce((t, v) => t + v, 0);

    let rightTotal = arr.slice(i + 1).reduce((t, v) => t + v, 0);

   

    if (leftTotal === rightTotal) {

      return leftTotal; // find total left or right

    }

  }

  return -1;

}

console.log(findEvenIndex([1,2,3,4,5,4,3,2,1]))

2. Mencari sebuah index dari array 

function findEvenIndex(arr) {

  let index = -1;

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

    let start = arr.slice(0, i+1).reduce((a, b) => a + b, 0);

    let end = arr.slice(i).reduce((a, b) => a + b, 0)

    if (start === end) {

      index = i

    }

  }

  return index;

}

console.log(findEvenIndex([1,2,3,4,3,2,1]))


 

Cek String Jika Tipe String Huruf Kecil Semua

 


  function XO(str) {

    var x = [];

    var o = [];

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

        if (str[i].toLowerCase() === 'x') { 

            x.push(str[i]); 

        } else if (str[i].toLowerCase() === 'o') {

            o.push(str[i]);

        }

    }

    if (x.length == o.length) {

        return true;

    } else {

        return false;

    }

}

console.log(XO('xo'));

console.log(XO('xxo'));

console.log(XO('xoX'));

console.log(XO('xoOX'));


Membuat Huruf Depan Kapital dengan Vanila Javascript

function capitalize(str) {

  strVal = '';

  str = str.split(' ');

  for (var chr = 0; chr < str.length; chr++) {

    strVal += str[chr].substring(0, 1).toUpperCase() + str[chr].substring(1, str[chr].length) + ' '

  }

  return strVal;

}


console.log(capitalize('hello world post'));

 

Membaca Value Form Input Type Radio Javascript

 1. Form

 <input type="radio" name="usia" value="Gen X">

  <input type="radio" name="usia" value="Gen Z">

  <button onclick="check()">check</button>

2. Javascript

function check(){

var usia = document.querySelector('[name=usia]:checked').value;

console.log(usia)

}

Membaca Value Form Input Type Checkbox dengan Vanilla Javascript

 

1. Form

  <input type="checkbox" name="nama[]" value="robert">

  <input type="checkbox" name="nama[]" value="edward">

<button onclick="check()">Check</button>

2. javascript

 function check() {

    var list = [];

    var cboxes = document.getElementsByName('nama[]');

    var len = cboxes.length;

    for (var i = 0; i < len; i++) {

      if(cboxes[i].checked){

          list.push(cboxes[i].value)

      }

    }

    console.log(list.join(",").toString());

  }

Membuat Bilangan Prima Dengan Vanilla Javascript

 function isPrime(nums) {

  if(nums < 2 ){

      return false; 

  }  

  for(let i = 2; i < nums; i++){

      if(nums % i == 0){

        return false // modulus

      }

  } 

  return true; 

}

console.log(isPrime(2)) true

console.log(isPrime(4)) false

console.log(isPrime(5)) true

console.log(isPrime(6)) false

console.log(isPrime(7)) true

console.log(isPrime(9)) false

Tuesday, April 11, 2023

Blob Javascript


 

<script>

    const data = "Hai Muhammad Rifqi";


    const bl = new Blob([data], {type:'text/plain'});

    const url = URL.createObjectURL(bl);

    console.log(url)


    const a  = document.createElement("a");

    a.href = url;

    a.download = 'laporan.txt';

    a.click()


</script>

Monday, February 27, 2023

Membuat Api Pagination dengan PHP MYSQL

API PHP SCRIPT

      <?php

      error_reporting(0);

      header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Credentials: true");

header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS");

header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

header("Content-Type: application/json; charset=utf-8");

$koneksi = mysqli_connect("localhost","root","","db_toko_online");

$batas=2;

$halaman=$_GET['halaman'];

if(empty($halaman)){

$posisi=0;

$halaman=1;

}else{

$posisi=($halaman-1)*$batas;

}

$sql = mysqli_query($koneksi,"select * from produk limit $posisi,$batas");

$row = array();

while($data = mysqli_fetch_assoc($sql)){

$row[] = $data;

}

echo json_encode($row);

?>

CALL DATA API PHP

<?php

    error_reporting(0);

if(empty($_GET['halaman'])){

$data = file_get_contents('http://localhost/testing-disini/trik/api_paging.php');

}else{

$data = file_get_contents('http://localhost/testing-disini/trik/api_paging.php?halaman='.$_GET['halaman']);

}

$array = json_decode($data,true);

for($i=0;$i<count($array);$i++){

echo "<p>".$array[$i]['id_produk']."/".$array[$i]['nama_produk']."</p>";

}


$total = 9;

for($i=1;$i<=$total;$i++){

if ((($i >= $_GET['halaman'] - 3) && ($i <= $_GET['halaman'] + 3)) || ($i == 1) || ($i == $total)){

echo "<a href='?halaman=".$i."'>".$i."</a> | ";

}

}

?>



Friday, February 24, 2023

Cookie Vanilla Javascript


 

1. Set Cookie

 document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

2. Get Cookie

let cookie = {};

        var a = document.cookie.split(';');

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

            var b = a[i].split('=');

                var [key, value]  = b;

                cookie[key.trim()] = value;

        }

  console.log(cookie['_ga']);

3. ChangeCookie 

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Saturday, February 18, 2023

Format Number PHP dan JS

 1. php

<?php

function rupiah($angka){

$hasil_rupiah = "Rp " . number_format($angka,0,',','.');

return $hasil_rupiah;

}

echo rupiah(1000000);

?>


2. Js

<script>

let Rupiah = new Intl.NumberFormat('id-ID');

console.log(` ${Rupiah.format(123958)}`);

</script>

Set Cookie dan Remove Cookie dengan php vanilla.js

< html lang = "en" > < head >     < meta charset = "UTF-8" >     < meta name = "viewport...