Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Hendrik /
13,961 PointsCheck if email input is valid
Hey!
I've built a little email form and wanted to check with JavaScript and some jQuery if the email from the user is a valid. I thought if there is a simple '@' in the input, the email counts as valid and used indexOf to check if @ is existing. If there isn't a @ yet, a hint is shown with jQuery (jQuery Basics Course). My problem is that the hint won't disappear, once I enter a @ .
Here's my code
<form>
<h1>Stay up to date!</h1>
<label for="email">Email:</label>
<span id="hint">Enter a valid email!</span>
<input type="text" id="email" name="user_email">
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</form>
// Variables
var $hint = $("#hint");
var $email = $("#email").val();
//Hide hint
$hint.hide();
// Check if input contains @ symbol
function checkifValidEmail() {
var input = document.getElementById("email");
if(input.innerHTML.indexOf("@") !== -1 ) {
$hint.hide();
}
else{
$hint.show();
}
}
// show hint if you focus or keyup
$("#email").focus(checkifValidEmail).keyup(checkifValidEmail);
Thank you!
2 Answers
Steven Parker
243,318 Points
It looks like you are testing the wrong element property.
Try using value instead of innerHTML:
if (input.value.indexOf("@") !== -1) {
Cindy Lea
Courses Plus Student 6,497 PointsTry $form.submit(remove);
Hendrik /
13,961 PointsHi Cindy! Where exactly would you try it and why?
Steven Parker
243,318 PointsThat had me stumped also.
Hendrik /
13,961 PointsHendrik /
13,961 PointsGreat thank you Steven! :)