Reputation: 25
I am learning javascript recently. Now am trying to show a div after the form is submitted along with the validation of the input field. Means if the input is blank the div will not show, and if the form is submitted along with the fields then the div will show. I have managed to show and hide div on the submit button, but the form is not checking the validation of input, it is submitting along with the empty div. Below is the code
HTML
<form method="post" action="#" id="form" class="form" >
<div class="agent-details" id="agy">
<ul class="agent-information list-unstyled">
<li class="agent-link">
<a href="#">View Listings</a>
</li>
</ul>
</div>
<div class="form-group">
<input class="form-control" id="name" name="name" value="" type="text" placeholder="Name">
</div><!-- form-group -->
<button type="button" onclick="mySub();"> Send Message </button>
</form>
JAVASCRIPT CODE
function mySub()
{
const user = document.getElementById('name').value;
const username = user.value;
if (username === "")
{
document.getElementById('agy').style.display = 'none';
}
else
{
document.getElementById('agy').style.display = 'block';
}
}
Upvotes: 1
Views: 662
Reputation: 706
I see your problem is the way you access value from "name" input.
const user = document.getElementById('name').value;
const username = user.value;
The problem is in const username = user.value;
You already got username value in "user" variable, but somehow you did it twice here, with this statement: user.value, you don't need to do that. Because you tried to access 'value' property of the string you got undefined which is not what you want.
Just replace it with:
const username = document.getElementById('name').value;
and remove:
const username = user.value;
Also I created the fiddle so you can try it: https://jsfiddle.net/yc14qto5/
Upvotes: 1