Javascript

Title Code
single quote ( ' ) in JavaScript
alert("Sorry user! Your account don't create successfully. Please try again.");

NB: Just use 'backslash'  before any single or double quotetion.
Js print only this quation not 'backslash'

https://www.w3schools.com/js/js_strings.asp
alert
Html
@if (session('success'))
                           <div class="alert alert-success">
                              <strong>Success!</strong> {{ session('success') }}
                           </div>
@endif

js include
then
<script type="text/javascript">
      window.setTimeout(function() {
          $(".alert").fadeTo(500, 0).slideUp(500, function(){
              $(this).remove(); 
          });
      }, 2000);
</script>
defer
<!doctype html>
<body>
<p>...content before scripts...</p>

<script>
  document.addEventListener('DOMContentLoaded', () => alert("(1) DOM ready after defer!")); // (2)
</script>

<script defer src="https://javascript.info/article/script-async-defer/long.js?speed=1">
</script>

<script>
  document.addEventListener('DOMContentLoaded', () => alert("(2) DOM ready after defer!")); // (2)
</script>



<p>...content after scripts...</p>
</body>
first letter capital
<div  class="alert alert-success">
                              <strong>Success!</strong> {{ session('success') }}
                           </div>

<script type="text/javascript">
      $(".alert").each(function(){
        var txt =  $(this).text().replace(/\s+/g,' ').trim() ;
        $(this).text(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
      });
   </script>
JQuery .on('click') not working in DataTables 2nd page
https://stackoverflow.com/questions/25414778/jquery-onclick-not-working-in-datatables-2nd-page-or-rows-past-11
js clock
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>Simple setInterval clock</title>
    <style>
      p {
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <p class="clock"></p>
    <script>
      function displayTime() {
        let date = new Date();
        let time = date.toLocaleTimeString();
        document.querySelector('.clock').textContent = time;
      }

      displayTime();
      const createClock = setInterval(displayTime, 1000);
    </script>
  </body>
</html>
onclick action
<!DOCTYPE html>
<html>
<body>

<button class="btn copy" onclick="abc(this)">Copy</button>

<script>
  function abc(obj) {
    obj.style.backgroundColor = "blue";
    obj.style.color = "#fff";
    obj.innerHTML = "Copied";
    document.getElementById("demo").style.backgroundColor = "blue";
  }
</script>

<p id="demo" style="width:120px; height:120px; background-color:cyan;"></p>


</body>
</html> 
onclick default color
<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">

function setToRed ( )
{
  document.getElementById("colourButton").style.color = "#FF0000";
  setTimeout ( "setToBlack()", 2000 );
}
clearInterval(setToBlack ( ));
function setToBlack ( )
{
  document.getElementById("colourButton").style.color = "#000000";
}

</script>

<input type="button" name="clickMe" id="colourButton" value="Click me and wait!" onclick="setToRed()"/>
</body>
</html>
setTimeout
<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Try it</button>
<p id="demo" style="width:100px; height:100px; background-color:cyan;"></p>
<script>

function myFunction() {
  var myVar = setTimeout(alertFunc, 2000);
}
function alertFunc() {
  document.getElementById("demo").style.backgroundColor = "blue";
}
</script>

</body>
</html>
Selector
<table class="table table-bordered text-center">
        <tr>
            <td>HTML</td>
            <td>Jquery</td>
        </tr>
        <tr>
            <td>
                <p>This normal selector</p>
            </td>
            <td>
                $("p").text("This normal selector2");
            </td>
        </tr>
        <tr>
            <td>
                <h4>Selector bold</h4>
            </td>
            <td>
                $("h4").html(<b>Selector bold2</b>);
            </td>
        </tr>
        <tr>
            <td id="newId">Id selector</td>
            <td>
                $("#newId").html("<b>Id selector2</b>");
            </td>
        </tr>
        <tr>
            <td class="newClass">Class selector</td>
            <td>
                $(".newClass").html("<b>Class selector2</b>");              
            </td>
        </tr>

        <tr class="parent">
            <td class="child">
                <h4>This is nested selector</h4>
            </td>
            <td>
                $(".parent .child h4").html("<b>This is nested selector2</b>");
            </td>
        </tr>
      </table>
ajax response type
$.ajax({	
	success: function (response) {
		alert(response);
	},
	failure: function (response) {
		alert(response.responseText);
	},
	error: function (response) {
		alert(response.responseText);
	}
});
button disable
<button class="without_p" id="without_p">Order Without Print</button>
<button class="with_p" id="with_p">Order With Print</button>

Nb: class not working sometime


    document.getElementById("without_p").disabled = true;
    document.getElementById("with_p").disabled = true;
    document.querySelector('#with_p').disabled = true;
autoFocus
<dialog id="favDialog">
                            Phone: <input type="text" name="mnfr" autofocus>
                        </dialog>
                        <menu>
                            <a class="btn btn-success" id="phoneDetails">Tell us about your phone</a>
                        </menu>


<script>
    var chooseButton = document.getElementById('phoneDetails');
    chooseButton.addEventListener('click', function onOpen() {
        if (typeof favDialog.showModal === "function") {
            favDialog.showModal();
        } else {
            alert("The <dialog> API is not supported by this browser");
        }
    });
</script>




    $(document).on("click", ".autoFocus", function () {
        alert('12');
        $('#cash').find('[autoFocus]').focus();
        $('#cash').focus();
    });



    function autoFocus(){
        $('.payment_reload').on('shown.bs.modal', function () {
            alert('123');
            $('#cash').focus();
        });
    }
append index number
<div>
                            <div id="input-container">
                                <input type="text" id="input0" value="Existing Input">
                            </div>
                            <button onclick="addInput()">Add Input Field</button>
                            
                            <script>
                                let inputIndex = 1;                            
                                function addInput() {
                                    const inputContainer = document.getElementById('input-container');
                                    const input = document.createElement('input');
                                    input.type = 'text';
                                    input.id = 'input' + inputIndex;
                                    input.value = 'New Input ' + inputIndex;
                                    inputContainer.appendChild(input);                                    
                                    inputIndex++;
                                }
                            </script>
                        </div>
PHP Notification Tutorial
https://www.cloudways.com/blog/real-time-php-notification-system/
put cursor at end of text input's value
js.cdn
<input type="text" id="txt1" value="Lorem"/>
$(function() {
      var input = $("#txt1");
    var len = input.val().length;
    input[0].focus();
    input[0].setSelectionRange(len, len);
    });



https://stackoverflow.com/questions/17780756/put-cursor-at-end-of-text-inputs-value
enter press and move another field
<div class="row justify-content-center">
        <div class="col">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" autofocus>
        </div>
        <div class="col">
            <label for="email">Email</label>
            <input type="email" class="form-control" id="email" placeholder="type and press enter">
        </div>
        <div class="col">
            <button type="submit" class="btn btn-primary mt-4 px-5" onclick="javascript:alert('You press #Enter button#!')" id="submit">Submit</button>
        </div>        
    </div>

<script>
        $("#name").keypress(function(e) {
            if(e.which == 13){
                $('#email').focus();
            }
        });

        $("#email").keypress(function(e) {
            if(e.which == 13){
                $('#submit').focus();
            }
        });
    </script>
image upload with JavaScript
https://uploadcare.com/learning/file-uploader/js-image-upload/
loader
html
<div id='loader' style='display: none;'></div>

Ajax
    function combo_event($id) {
        var item_id = $id;
        $("#loader").show();
        $.ajax({
            url: "includes/combo_item_list.php",
            method: "POST",
            data: {
                item_id: item_id
            },
            dataType: "json",
            success: function(data) {
                $("#loader").hide();
            }
        });
    };

CSS


#loader{
    /* position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999; */
    /* background: url('//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif') 50% 50% no-repeat rgb(249,249,249); */
    /* background: url('loader.gif') 50% 50% no-repeat rgb(249,249,249); */
    /* background-color: transparent; */    
}

#loader {
    position:fixed;
    width:100%;
    left:0;right:0;top:0;bottom:0;
    background-color: rgba(255,255,255,0.7);
    z-index:9999;
    display:none;
}

or...........
@-webkit-keyframes spin {
	from {-webkit-transform:rotate(0deg);}
	to {-webkit-transform:rotate(360deg);}
}

@keyframes spin {
	from {transform:rotate(0deg);}
	to {transform:rotate(360deg);}
}

#loader::after {
    content:'';
    display:block;
    position:absolute;
    left:48%;top:40%;
    width:40px;height:40px;
    border-style:solid;
    border-color:black;
    border-top-color:transparent;
    border-width: 4px;
    border-radius:50%;
    -webkit-animation: spin .8s linear infinite;
    animation: spin .8s linear infinite;
}
progress-bar
<div class="container">
        <div class="progress">
            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
    </div>


<script>
    for(var i=1; i<=10; i++){
        doSetTimeout(i);
    }

    function doSetTimeout(i){        
        setTimeout(function() {
            var j = i*10;
            $('.progress-bar').attr('aria-valuenow', j).css('width', j + '%').text(j + '%');
        }, i*1000);
    }
</script>

https://shareurcodes.com/blog/real%20time%20progress%20bar%20in%20php
progress-bar2
<div class="container mt-4">
    <div class="progress">
        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
    </div>
</div>

<div class="container mt-4">
    <div id="progressbar" style="border:1px solid #ccc; border-radius: 5px; "></div>
    <br>
	<div id="information" ></div>
</div>


<?php
    $total = 100;    
    for($i=1; $i<$total; $i++){
        $percent = intval($i/$total * 100)."%";

        sleep(1);

        echo 
            '<script>
                parent.document.getElementById("progressbar").innerHTML="<div style=\" width:'.$percent.'; background: #f00; height:35px; \"> &nbsp; </div>";
                parent.document.getElementById("information").innerHTML="<div style=\" text-align:center; font-weight:bold \">' .$percent. ' is processed.</div>";
            </script>';

        echo "<script> 
            $('.progress-bar').attr('aria-valuenow', $i).css('width', $i + '%').text($i + '%');            
        </script>";

        ob_flush();
        flush();

        $i = $i+9;
    }
    echo 
        '<script>
            parent.document.getElementById("information").innerHTML="<div style=\" text-align:center; font-weight:bold \">Process completed</div>";
        </script>';
?>
progress-bar dynamic
bootstrap

<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title" id="exampleModalLabel">Upload online database</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

                <div id="one" style="display: none;">
                    <label for="">1st table invoice upload</label>
                    <div class="progress">
                        <div class="one progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
                <div id="two" style="display: none;">
                    <label for="">2nd table Invoice upload</label>
                    <div class="progress">
                        <div class="two progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>

            </div>
            <div class="modal-footer py-2">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>


<?php
    echo "<script> $('#myModal').modal('show'); </script>";

    $tables = ['one' => 4, 'two' => '5'];

    foreach($tables as $key => $total){
        for($i = 0; $i <= $total; $i++){
    
            echo "<script> $('#$key').show(); </script>";
    
            $percent = intval($i / $total * 100);
            setTime(1);
    
            echo
                "<script>
                    $('.$key').attr('aria-valuenow', $percent).css('width', $percent + '%').text($percent + '%');
                </script>";
            
            flushLoad();
        }
    }

    sleep(1);
    echo "<script> $('#myModal').modal('hide'); </script>";

    function setTime($n){
        return sleep($n);
    }
    
    function flushLoad(){
        ob_flush();
        flush();
    }
    echo "<script> location.href='index.php'; </script>";
?>
progress-bar final
<?php
    session_start();
    include("includes/header.php");
    include("includes/db_connect.php");
    include("includes/footer.php");
?>


<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h5 class="modal-title" id="exampleModalLabel">Upload online database</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body pb-2 pt-0">
                <!-- <div id="one" style="display: none;">
                    <label for="">1st table invoice upload</label>
                    <div class="progress">
                        <div class="one progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
                <div id="two" style="display: none;">
                    <label for="">2nd table Invoice upload</label>
                    <div class="progress">
                        <div class="two progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div> -->
            </div>
        </div>
    </div>
</div>


<?php
    echo "<script> $('#myModal').modal('show'); </script>";

    $tables = ['info' => 2, 'secondary' => '2', 'dark' => '2', 'primary' => '2', 'success' => '2','warning' => '2', 'danger' => '2'];
    $loop = 0;
    $colors = array('bg-info', 'bg-secondary', 'bg-dark', 'bg-primary', 'bg-success', 'bg-warning', 'bg-danger'); 

    foreach($tables as $key => $total){  
        echo $colors[$loop] ."<br>";

        echo
            "<script>
                var divName = '<div id=\"$key\"><label class=\"mb-0\">$key</label><div class=\"progress\"><div class=\"$key $colors[$loop] progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div></div></div>';                  
                $('.modal-body').append(divName);
            </script>";

        for($i = 0; $i <= $total; $i++){    
            // echo "<script> $('#$key').show(); </script>";
    
            $percent = intval($i / $total * 100);
            setTime(1);
    
            echo
                "<script>
                    $('.$key').attr('aria-valuenow', $percent).css('width', $percent + '%').text($percent + '%');
                </script>";
            flushLoad();
        }
        $loop++;
    }

    sleep(5);
    echo "<script> $('#myModal').modal('hide'); </script>";

    function setTime($n){
        return sleep($n);
    }
    
    function flushLoad(){
        ob_flush();
        flush();
    }
    echo "<script> location.href='index.php'; </script>";
?>
onKeyPress, onKeyUp
<html>
<body>
    <input id="edValue" type="text" onKeyPress="edValueKeyPress()" onKeyUp="edValueKeyPress()"><br>
    <span id="lblValue">The text box contains: </span>
</body>

<script>
    function edValueKeyPress()
    {
        var edValue = document.getElementById("edValue");
        var s = edValue.value;
    
        var lblValue = document.getElementById("lblValue");
        lblValue.innerText = "The text box contains: "+s;
    
        //var s = $("#edValue").val();
        //$("#lblValue").text(s);    
    }
</script>    

</html>


https://jsfiddle.net/VDd6C/8/
autofocus
<button onclick="discountModal('modalName')">Discount</button>
<div class="modal fade" id="modalName" data-backdrop="static">
<input type="number" id="discount" autocomplete="off">
</div>

function onclickModal(){
        $('#modalName').modal('show');
        $('#modalName').on('shown.bs.modal', function () {
           $('#discount').focus();
        });
    }
Dynamic
function onclickModal($name){
        var name = $name;
        $('#'+name).modal('show');
        $('#'+name).on('shown.bs.modal', function () {            
            $('#'+name+' input').focus(); 
        });
    }
How can I check if a checkbox is checked?
<div class="form-group form-check">
                            <input type="checkbox" class="form-check-input" id="approve">
                            <label class="form-check-label" for="approve">Appointment approve?</label>
                        </div>

if (document.getElementById('approve').checked) {
            alert("checked");
        } else {
            alert("You didn't check it! Let me check it for you.");
        }


https://stackoverflow.com/questions/9887360/how-can-i-check-if-a-checkbox-is-checked
get data attribute value of selected option
<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>

You need to find the selected option:

$(this).find(':selected').data('id')
or

$(this).find(':selected').attr('data-id')
although the first method is preferred.


 <select class="form-control" id="category" name="category" required>
                                                        <option for="123" value="">Select a Type</option>

 $(document).on("change", "#category", function() {
        // var category = document.querySelector("#category");
        // var value = category.options[category.selectedIndex].getAttribute('for');
        var value = $(this).find(':selected').attr('for')
        console.log(value);
}

        var value = $("#category").find(':selected').attr('for')