Paul
Paul

Reputation: 101

Populate hidden field with autocomplete value

I have an HTML form with a regular text input and a hidden field.

I also have the following code that will populate the hidden field with the value of the text field either when it is changed, or if the text field has a default value (supplied by the page itself):

$(document).ready(function() {
  var emailinput = document.getElementById('emailval');

  document.getElementById('usernameval').value = emailinput.value;

  emailinput.onkeyup = function() {
    document.getElementById('usernameval').value = emailinput.value;
  }

  emailinput.onblur = function() {
    document.getElementById('usernameval').value = emailinput.value;
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="email" id="emailval" />
<input type="hidden" name="username" id="usernameval" />

This works well, except in the case where the browser autofills the text field. If the user submits the form without changing the textfield.

So my question is, is there any way to have the javascript pull the value from the browser-autofilled text field?

Upvotes: 0

Views: 1973

Answers (3)

Sean Mishra
Sean Mishra

Reputation: 309

You could use the form's onsubmit event. Here's the pseudo code:-

form.onsubmit= function(e){
  e.preventDefault();
  document.getElementById('usernameval').value = document.getElementById('emailval').value;
  this.submit();
}

Upvotes: 0

andrralv
andrralv

Reputation: 860

What is 'input7'? I'm assuming this is a key. You could add another event for when the mouse leaves the input box, to get that value, since the user has to use the mouse to select the value.

Another thing you might want to consider, is turn off autocomplete on that field. https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion

Upvotes: 0

Dylon
Dylon

Reputation: 1750

Attach an event handler on the form's submit event, and copy the value of #emailval to #usernameval. For example, let's say your form has the ID, #form:

$('#form').submit(function (event) {
  'use strict';
  $('#usernameval').val($('#emailval').val());
});

Documentation: https://api.jquery.com/submit/

Upvotes: 2

Related Questions