0

I would like to trigger a left button keypress when the user focuses in on an input text field. So far, my code only selects the default value but does not trigger a left button keypress. I actually do need the default value in the text field.

I have:

<label for="name">Name</label>
<input id="name" type="text">
<label for="email">Email</label> 
<input id="email" type="email" value="@somemail.com">

I've tried:

$('#email').on('focus', function() {
     $(this).trigger($.Event('keypress', {keyCode: 37}));
});

based on JQuery simulating keypress event on an input field but to no avail. Here is a fiddle: https://jsfiddle.net/c9n39r53/

I would like to see this when the form focuses on the email input field:

Community
  • 1
  • 1
joncoded
  • 125
  • 2
  • 7
  • And what happens when the left arrow is pressed, do you have an event handler for that as well, or are you just expecting the cursor to move for some reason? – adeneo Sep 20 '16 at 20:36
  • Are you trying to prevent someone from altering the the `@somemail.com` portion of the string? If that's so, then just don't put it in the ``, put it *beside* the ``. – David Thomas Sep 20 '16 at 20:43
  • 1
    Maybe this is it ? -> https://jsfiddle.net/adeneo/c9n39r53/2/ – adeneo Sep 20 '16 at 20:50
  • @DavidThomas I'm not trying to prevent anyone from altering @somemail.com; it's just aesthetic because I already have another validation for it – joncoded Sep 20 '16 at 21:35
  • @adeneo thanks, I just needed a left arrow key pressed so that the user is able to type their pre-@ part of their e-mail address and then move on – joncoded Sep 20 '16 at 21:35
  • Additional note: It won't work if the input type is "email" but will do just fine if the type is "text" – joncoded Sep 20 '16 at 21:48

1 Answers1

1

For what is my understanding your plan is to force the placement of the cursor on the begining of the e-mail input.

$('#email').on('focus', function() {
    var elem = $(this)
    setTimeout(function(){
    elem.get(0).setSelectionRange(0,0,0);
  },100);
});

Here's my update to your fiddle

Which is a solution like @adeneo proposed. In fact, his is better since it has absolutely no delay.

On your fiddle, you also forgot to include JQuery.