First, make your markup more portable / reusable. I also set the button type to 'button' instead of using the onsubmit attribute. You can switch the type attribute for submit if the form should interact with the server.
<div class='wrapper'> <form id='nameForm'> <div class='form-uname'> <label id='nameLable' for='nameField'>Create a username:</label> <input id='nameField' type='text' maxlength='25'></input> </div> <div class='form-sub'> <button id='subButton' type='button'>Print your name!</button> </div> </form> <div> <p id='result'></p></div> </div>
Then write a generic function to extract the username into a variable. It checks to see if the variable containing the username contains at least three characters. You can change this to whatever constant you want.
function getUserName() { var nameField = document.getElementById('nameField').value; var result = document.getElementById('result'); if (nameField.length < 3) { result.textContent = 'Username must contain at least 3 characters';
Then I created an event listener for the button. It is generally considered bad practice to have inline js calls.
var subButton = document.getElementById('subButton'); subButton.addEventListener('click', getUserName, false);
Here's a working and slightly styled demo:
CodePen demonstration of this answer.
source share