JS Snippets

Trigger Button Click on Enter

Press the "Enter" key inside the input field to trigger the button.

Code

HTML

<h3>Trigger Button Click on Enter</h3>
<p>Press the "Enter" key inside the input field to trigger the button.</p>

<label for='txt'>Text</label>
<input id="myInput" placeholder='Enter some text' id='txt'>
<button id="myBtn" onclick="javascript:alert('Hello World!')">Button</button>

JS

<script>
    var input = document.getElementById("myInput");
    input.addEventListener("keyup", function(event) {
        if (event.keyCode === 13) {
        event.preventDefault();
    document.getElementById("myBtn").click();
        }
    });
</script>

Show Password

Enter a Password

Password:

Code

HTML

<h4>Enter a Password</h4>
<input type="checkbox" onclick="showPassword()" id='pw'>
<label for='pw'>Show Password</label>

JS

<script>
function showPassword() {
    var x = document.getElementById("pwInput");
    if (x.type === "password") {
        x.type = "text";
    } else {
        x.type = "password";
    }
}
</script>

Trigger Checkbox

Code

HTML

<h3>Trigger Checkbox</h3>

<label for='chk'>Checkbox: </label>
<input type="checkbox" id="chk" onclick="triggerCheck()">
<p id="text" style="display:none">Checkbox is CHECKED!</p>

JS

<script>
  function showPassword() {
    function triggerCheck() {
    // Get the checkbox
    var checkBox = document.getElementById("chk");
    // Get the output text
    var text = document.getElementById("text");

    // If the checkbox is checked, display the output text
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
        text.style.display = "none";
    }
  }
</script>

Clear Input Field

Clear the input field when it gets focus:

Clear the input field when you click on the button:

Code

HTML

<p>Clear the input field when it gets focus:</p>
<input type="text" onfocus="this.value=''" value="Click here to clear">

<p>Clear the input field when you click on the button:</p>
<button onclick="document.getElementById('myInput').value = ''">Clear </button>

<input type="text" value="Click button to clear" id="myInput">