In this blog post, we will discuss, how you can show or hide an input field for password using plain HTML and Javascript. This is useful because sometimes users wants to see what password they are setting. This feature is very helpful in:
Signup, because user will be entering his password for the first time.
Reset, because user wants to know what new password he is setting-up.
No library has been used in this tutorial.
First, we will create an input field for password.
<!-- input field for password -->
<input type="password" id="password" />
Then, we will create a button that will show or hide the password.
<!-- button to toggle show/hide -->
<button type="button" onclick="togglePassword()">Show/hide</button>
Finally, we will create a Javascript function that will change the type of password input field.
// function to toggle password
function togglePassword() {
// get password input field
const password = document.getElementById("password")
// change input type to password if currently is text, and change to text if currently is password
password.type = (password.type == "password") ? "text" : "password"
}
This function will first get the DOM of input field for password. Then it will execute a ternary operator to check if the current type is “password”, meaning the password is hidden, then it will set it’s type to “text” and the password will be visible to the user.
And if currently the type is “text”, it means that user is currently viewing the password, then it will set it’s type to “password” and hence hide the password.
Complete source code:
<!-- input field for password -->
<input type="password" id="password" />
<!-- button to toggle show/hide -->
<button type="button" onclick="togglePassword()">Show/hide</button>
<script>
// function to toggle password
function togglePassword() {
// get password input field
const password = document.getElementById("password")
// change input type to password if currently is text, and change to text if currently is password
password.type = (password.type == "password") ? "text" : "password"
}
</script>
Above code will create an input field and a button. By default, what you enter in the input field will not be visible to you. But once you press the button, the password will be visible. And on again pressing the button, it will be hidden. That’s how you can show or hide an input field for password using simple HTML and Javascript.
Suppose you are creating a tab layout where there are multiple tabs and each tab has its own content. You click on the tab button and its content is displayed.
But when you refresh the page, it starts from the first tab again. How can you make so that when you refresh the page, it keeps the last active tab as “active” ?
Bootstrap Tabs
Following code will display a tab layout with 3 tabs in Bootstrap 5:
Right now it makes the “Home” tab active. When you click on other tabs, you will see their content. But once you refresh the page, it will again make the home tab active regardless of which tab you clicked last time.
Updating URL
Next step is to set the value of current tab in the URL when user changes the tab. So on each tab button, we will add an onclick listener that will call a function to update the URL in the browser.
If you want to learn more about this in detail, you can read this article.
If you change the tabs now, you will see that the “tab” query will be appended in the URL and its value will be the tab clicked. But if you refresh the page now, the tab will not be highlighted yet. This is because we are setting the “tab” query in URL but not reading it.
Highlight current tab as active
Last step is to get the current tab from the URL and highlight it.
<?php
$tab = $_GET["tab"] ?? "home";
?>
This is get the “tab” query from URL parameter. If it does not exists in the URL, then the default value of $tab variable will be “home”.
Following is the updated code that will highlight the tab button and also will show its content.
Following is the complete code that displays 3 tabs along with their contents. On change, will set the query parameter in the URL. After refresh will highlight the tab last selected.
If you are using the DataTable Javascript library and are having trouble searching in all fields of the dataset except for the only one visible, then I will show you, how you can search in all fields of the DataTable.
By default, DataTable searches in all fields only on those fields that are visible on the table. Let’s say you have a dataset containing “name”, “designation”, and “country” fields. But you are displaying only “name”, and “designation” on the table.
In this article, I am going to show you how you can show an ellipsis on a long text using HTML and CSS. We will be using just 4 CSS properties.
Video tutorial:
For example, you have a paragraph like this:
<p>A quick brown fox jumps over the lazy dog.</p>
Then give it a width and you will start seeing it in wrap.
<p style="width: 200px;">A quick brown fox jumps over the lazy dog.</p>
To disable the wrap, you can give the following property:
<p style="width: 200px;
white-space: nowrap;">A quick brown fox jumps over the lazy dog.</p>
Last thing you need to do, is to show ellipsis. To do that, just give the following 2 properties.
<p style="width: 200px;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: block;">A quick brown fox jumps over the lazy dog.</p>
So that’s it. That’s how you can show an ellipsis on a long text using just HTML and CSS. If you face any problem in following this, kindly do let me know.
In this article, we are going to discuss 2 options that how you can prevent your HTML form submit event from reloading the page. Normally, when you submit the form, it redirects to the action attribute link. But you can stop that reload and call an AJAX or any other Javascript function.
1. preventDefault
You can call the preventDefault function on the event target and it will stop the form from redirecting to the page specified in the action attribute of the <form> tag.
Then you can create the following Javascript function to prevent the page reload:
function onFormSubmit() {
event.preventDefault();
// your Javascript code here
}
In this method, the form is first prevented from submission and then your Javascript code will be run. So it prevents the form submit event first, then it will run our Javascript code which is a good approach.
You can learn more about preventDefault from here.
2. return false
The second approach is to use the return false statement in your Javascript code. For this, you also need to return the value from the onsubmit event function. Let’s check this out.
Then create your Javascript function as like that:
function onFormSubmit() {
// your Javascript code here
return false;
}
In this method, your Javascript code runs first before preventing the form submission.
Recommendation
We would recommend the 1st method i.e. preventDefault because it is the very first line of the Javascript function. So if there is an error in your Javascript code, your browser will not get reloaded and thus you will be able to view the error in the browser console.
Now that you have learned to prevent the form submit event. You can also display a pop-up for confirmation in case of the delete function. You can follow this tutorial to display a pop-up confirmation before submitting the form.
In this article, we are going to show you how you can display a beautiful message in a browser console using Javascript. You just need to download a library called Figlet.
After download, you need to extract the zip file and copy the file lib/figlet.js in your project. You also need to copy the fonts folder too.
Then you need to include that library in your project using the script tag:
<script src="figlet.js"></script>
Right after that, you can display the message you want in the browser console:
<script>
// initialize the library
const textDisplay = "adnan-tech.com";
const font = "Speed";
figlet(textDisplay, font, function (error, text) {
// display the text in console
console.log(text);
});
</script>
In this tutorial, we are going to show you, how you can show a sweetalert confirmation dialog when submitting a form. For example, if you have a form that when submits delete the data from the database. In that case, you must verify with the user because he might click that button by accident. So you can show a nice dialog using the Sweetalert library. Suppose you have the following form:
When the form submits, we are calling a Javascript function submitForm and passing the form as a parameter. Then you need to download the Sweetalert library from here. After downloading, paste that into your project and include it in your HTML file:
<script src="sweetalert.min.js"></script>
Now, we can create that Javascript function that will ask for confirmation. Once confirmed, it will submit the form.
<script>
function submitForm(form) {
swal({
title: "Are you sure?",
text: "This form will be submitted",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(function (isOkay) {
if (isOkay) {
form.submit();
}
});
return false;
}
</script>
At this point, if you submit the form, you will see a SweetAlert confirmation dialog first. All the form fields will be submitted correctly on the server-side. You can check it by printing out all the values received from the form:
When people use someone else’s computer and try to log in to their account on any website, they are afraid that the other person might have installed a Keylogging software that tracks all the keys pressed, and hence they will know his password. But if you show a custom keyboard view for a password field on your website, it will create a whole new level of confidence in users towards your website.
So let’s learn how you can do this.
This is what we are going to create:
First, you need to create a password field, you probably also have a username or email field as well.
We have written the normal key in the <span> tag and the shift key directly in <td>. Also, we have given data-shift and data-initial attribute so we can know which character to use when the shift key is pressed and which character to use when the shift key is released.
1st row (QWERTY):
This will be the very first row on your keyboard. You can compare it with your keyboard. Create a new <tr> tag in your table:
It also has data-shift and data-initial attributes that tell that the character will be uppercase when the shift key is pressed, and lowercase when the shift key is released.
2nd row (ASDF):
Similarly, we are going to create a second row of the keyboard.
This will make your keyboard look nice and readable.
Javascript
The real power of this keyboard view comes with Javascript. Following is the complete Javascript code that will make this static keyboard view functional.
var isShift = false;
window.addEventListener("load", function () {
var tds = document.querySelectorAll(".keyboard td");
for (var a = 0; a < tds.length; a++) {
tds[a].addEventListener("click", function () {
/* get key node */
var node = this.querySelector("span");
if (node == null) {
return;
}
if (node.innerHTML == "delete") {
simulateBackspace(document.getElementById("password"));
} else if (node.innerHTML == "shift") {
/* toggle the isShift variable */
isShift = !isShift;
toggleShift();
} else {
/* check if it is an alphabet */
if ((/[a-zA-Z]/).test(node.innerHTML)) {
document.getElementById("password").value += node.innerHTML;
} else {
/* show initial value if the shift is off.
* show shift value if shift is on. */
if (isShift) {
document.getElementById("password").value += node.getAttribute("data-shift");
} else {
document.getElementById("password").value += node.getAttribute("data-initial");
}
}
if (isShift) {
isShift = false;
toggleShift();
}
}
});
}
});
function toggleShift() {
/* make all alphabets capital or small based on new isShift value */
var keys = document.querySelectorAll(".keyboard span");
for (var b = 0; b < keys.length; b++) {
/* keys must not be shift or delete */
if (keys[b].innerHTML != "shift" && keys[b].innerHTML != "delete" && keys[b].innerHTML != "") {
/* check if it is an alphabet */
if ((/[a-zA-Z]/).test(keys[b].innerHTML)) {
if (isShift) {
keys[b].innerHTML = keys[b].innerHTML.toUpperCase();
} else {
keys[b].innerHTML = keys[b].innerHTML.toLowerCase();
}
}
}
}
/* highlight the shift button if on. */
if (isShift) {
document.getElementById("key-shift").className = "active";
} else {
document.getElementById("key-shift").className = "";
}
}
function simulateBackspace(element) {
var start = element.selectionStart, end = element.selectionEnd, event;
if (!element.setRangeText) { return; }
if (start >= end) {
if (start <= 0 || !element.setSelectionRange) { return; }
element.setSelectionRange(start - 1, start);
}
element.setRangeText("");
event = document.createEvent("HTMLEvents");
event.initEvent("input", true, false);
element.dispatchEvent(event);
}
That’s how you can create a fully functional custom numeric keyboard view. Comments have been added with each line for an explanation. You can customize this as much as you want. If you face any problems feel free to ask in the comment section below.
Learn how to add dynamic rows in a table tag in HTML and Javascript. And also save the data in MySQL database using PHP.
Introduction
Suppose you are trying to generate an invoice for your customers. You wanted to have a functionality where you will be able to add multiple items in an invoice. A simple table tag will be created from where the user will be able to add multiple items. You have added a button labeled as “Add Item” which when clicked will create a new row to add an item.
Now it might sound easy but technically you have to create rows dynamically. Whenever a user clicks on the “Add Item” button, a new row inside table tag should be created and it must be an array as items can be multiple. Then these arrays should be stored in the database using a loop iteration. Following this tutorial, you will be able to do so.
We will be creating 2 tables, although to explain this tutorial only 1 table would be enough but teaching with 2 will help to understand better when you are working on existing projects. We will have 1 table for storing invoices basic data, for example, customer name, etc, and the second table for storing items in that invoice.
“invoices” table
Our first table name is “invoices” and it will have just 2 fields, unique auto-increment ID and customer name. And the second table will be named “items” and have the product name, quantity, etc and also a foreign key that reference for invoice ID.
To add dynamic rows, we are using a <table> tag that will create a table layout so we will add rows in <tbody> tag. As discussed earlier, all rows will be in an array that needs to be stored in the database, so we will create a <form> tag that will help to do this. We are setting the method to POST as the data might be sensitive and long, and action attribute as current file name, you can change this if you want to send data to a different page.
Customer field
We are creating a simple input field for customer name that will be stored in the “invoices” table, you can place your other fields here. Then we are creating a <table> tag and inside it, we will be displaying the number of items, item name, and item quantity. Make sure to give <tbody> tag a unique ID so we can append new rows in it using Javascript.
Below them, we are creating a button which when clicked will call a Javascript function from where we can add a new row inside that table. And finally, a submit button which when clicked will submit the form and we have to save that data in database.
Now we need to create a function which when clicked will add a new node in the <tbody> tag. We have created a variable for the number of items and we are incrementing it on each click. Whenever this function called we are creating a <tr> tag and adding input fields for name and quantity in <td> tags. Notice the “[]” with the input name attribute, this tells that this field will be an array. Lastly, we are creating a new row using tbody function called insertRow() and appending the <tr> HTML in it.
<script>
var items = 0;
function addItem() {
items++;
var html = "<tr>";
html += "<td>" + items + "</td>";
html += "<td><input type='text' name='itemName[]'></td>";
html += "<td><input type='number' name='itemQuantity[]'></td>";
html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
function deleteRow(button) {
items--
button.parentElement.parentElement.remove();
// first parentElement will be td and second will be tr.
}
</script>
Style the table
Now we are going to apply some styles on our table just to make it look a little bit good.
Now we just need to store this data in our database. The following code must be put at the top of your file. Our database name is “tutorials” but it will be different in your case, make sure to change the DB name accordingly. Next, check if the form is submitted, the if block will only run after the user submits the form. Get the customer name and insert that in the “invoices” table, it is rather simple.
Remember we added “invoiceId” as a foreign key in “items” table. So, we have to get the newly inserted AUTO-INCREMENT ID. Then we are looping through all the added items. You can either use the “itemName” input field or “itemQuantity” and insert them in “items” table with same invoice ID.
That’s it, the job is done. At this point, you will be able to select multiple items. And add dynamic rows in table tag and inserting them in the database as well. Complete source file along with SQL exported file which will help you to understand the structure of database.
By the end of this tutorial, you will be able to send a dynamic email in PHP. Along with any beautifully designed template in HTML, CSS or Bootstrap. We will be using the template named “Invoice” from this website: https://www.dyspatch.io/resources/templates/airmail/
It’s a pretty basic template and great to learn. After downloading the template, you will see something like this:
All are static values. So let’s make them dynamic.
First you have to put all the template code in 1 separate file and named it “payment.php”, make sure to have all CSS code in this file. No external CSS file should be used because it will not appear in email.
Now, you have to replace the values you want to change and replace them with {{key}} for example, if you want to make coupon code dynamic, you will do something like this:
Coupon code {{coupon_code}}
Now, coming back to the file from where you want to send email, let’s say “send-mail.php”, first you have to get the template file by:
This will display your email template in “send-mail.php” file. In order to replace the {{coupon_code}} with your dynamic value, you have to use the str_replace function of PHP. It accepts 3 parameters:
Now we are going to add {{key}} on every static value in template which needs to be dynamic. After that, you need to create an array in your “send-mail.php” file and use the same function for all static values.
Hit the “send mail” button and you will receive an email similar to this:
So that’s how you can send a dynamic email in PHP from any HTML template. Also, learn how you can attach a link to the file to download in an email from here.
If you have any problems in following this, feel free to ask in the comments section below.