First, make your markup more portable/reusable. I also set the button's type to 'button'
instead of using the onsubmit
attribute. You can toggle the type
attribute to submit
if the form needs to interact with a 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>
Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. 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';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your username is: ' + nameField;
//alert(nameField);
}
}
Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
Here is a working and lightly styled demo: