How to Convert Hex to Octal Using JavaScript With HTML?

Hello Friends Today, through this tutorial, I will tell you How to Hex to octal Convert Using JavaScript Without Submit Button with HTML? You can create a simple HTML page that automatically converts a hexadecimal number to octal using JavaScript without a submit button. Here’s an example:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hex to Octal Converter</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
label {
display: block;
margin-bottom: 8px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h2>Hex to Octal Converter</h2>
<label for="hexInput">Enter Hexadecimal Number:</label>
<input type="text" id="hexInput" placeholder="Enter hexadecimal number" oninput="convertHexToOctal()">
<p id="result"></p>
<script>
function convertHexToOctal() {
// Get the hexadecimal input value
const hexInput = document.getElementById('hexInput').value;
// Validate the input as a valid hexadecimal number
if (!/^[0-9A-Fa-f]+$/.test(hexInput)) {
document.getElementById('result').innerHTML = 'Invalid hexadecimal number';
return;
}
// Convert hexadecimal to octal
const octalResult = parseInt(hexInput, 16).toString(8);
// Display the result
document.getElementById('result').innerHTML = `Octal: ${octalResult}`;
}
</script>
</body>
</html>

In this example, the `oninput` attribute is used in the input field, which calls the `convertHexToOctal` function whenever the user inputs a value. The script checks if the input is a valid hexadecimal number using a regular expression and then converts it to octal using the `parseInt` function. The result is displayed below the input field.