Add suffix to form field

2020-08-04 10:11发布

问题:

I have some (more than thousand) users that insist on logging in just with their names, but a system that insists on having the full e-mail address (name + @my-mail.com) provided. Which is a smart solution to add a suffix to a field without bothering the user?

The Form:

<form id="login_form" action="processing.php" method="post" class="form">
  <fieldset>
     <ul class="input_block">
        <li>
           <input type="text" name="email" id="email" value="" />
        </li>
        <li>
           <input type="password" name="passwort" id="password" />
        </li>
     </ul>
  </fieldset>

I played around with the key up function for the field, but it didn't help much.

<script>
$('#email').keyup(function(e){
   if(this.value.length > 12){
     this.value = this.value + '@my-mail.com';
  if( this.value.indexOf('@my-mail.com') <= 0 ){ 
     this.value = String.fromCharCode(e.which) + '@my-mail.com'; 
  }
});
</script>

I consider a solution that manipulates the field just right before the submission much more "proper" (sadly I don't have access to the PHP file that is receiving the submission). So I tried as well with the submit function, this didn't work either.

<script>
$( "#login_form" ).submit(function( event ) {
   ("#email").value = ("#email").value + '@my-mail.com';
});
</script>

Anybody some advise on how to solve it using the submit function or another idea that seems to be better?

回答1:

$('#email').change(function() {
  var val = $(this).val();
  if(val.indexOf('@my-mail.com') == -1)
    $(this).val(val+'@my-mail.com');
});

http://jsfiddle.net/g4oLtfw7/

This will add the '@my-mail.com' suffix if it's not already part of the input value. If you want to allow other types of emails, but default to 'my-mail.com' otherwise, try this:

$('#email').change(function() {
  var val = $(this).val();
  if(val.indexOf('@') == -1)
    $(this).val(val+'@my-mail.com');
});


回答2:

Either:

$('#login_form').submit(function (e) {
    var email = $('#email'),
        user = email.val().split('@')[0],
        domain = '@my-mail.com';
    if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
        email.val(user + domain);
    }
});

or

$('#email').change(function (e) {
    var email = $(this),
        user = email.val().split('@')[0],
        domain = '@my-mail.com';
    if (email.val().toLowerCase() !== (user + domain).toLowerCase()) {
        email.val(user + domain);
    }
});

is how I would approach this (obligatory fiddle: http://jsfiddle.net/e84v7nat/).

This approach ensures that your user has a domain specified and that the domain is correct. If the username is case-sensitive, remove the calls to .toLowerCase.