Skip to content

Javascript: check if word in input is placed after an other word

I have a question but I can’t find the answer for my problem. Hope you can help me!

Here’s my HTML:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="one">
    <input type="text" id="two">

Here’s my Javascript:

$('#one').on('input', function(){
var value = $(this).val();
if (value.includes("@") && value.includes(".com"))
{
   $('#two').focus();
   }
  });

Demo

What this script does
I’m making a login form where the input focuses on the second input when a user has typed his email. In my code: it focuses on the next input when the first input detects an ‘@’ symbol and the text ‘.com’.

But here’s the problem
Lets say your email is: ‘[email protected]’. My script focuses on the second input after you typed the ‘@’ symbol, because the input already contains ‘.com’ and ‘@’.

My Question
What javascript do I need to add that checks if ‘.com’ is typed after the ‘@’ symbol?

Answer

You could use regex: @.*.com

if (/@.*.com/.test(value))