mercredi 10 avril 2019

Trying to get the first 5 characters of input 1, and first character of input 2

I am trying to generate usernames for users based on the exisiting manual formula we use: first 5 characters of last name, first initial of first name.

Simple:

$("#first_name, #last_name").keyup(function(){
    var a = $("#first_name").val().substring(0, 1),
        b = $("#last_name").val().substring(0, 5);

    $("#username").val(b+a);
});

However, I have been trying to figure out the rules for when the last name is less than 5 characters, and then fill those missing characters with the next letters of their first name. And lastly if the first + last name is less than 5 characters in total, just add them.

This was something along the lines I was working towards, but it wasn't working and I can't seem to logic why:

$("#first_name, #last_name").keyup(function(){

    var a = $("#first_name").val(),
        b = $("#last_name").val();

    if( b < 5 ) {

        var c = ( 5 - b.length );

        if( c > a.length ) {
            var d = a.substring(0, c);
            $("#username").val( b + d );
        } else {

            $("#username").val( b + a );
        }

    } else {

        $("#username").val( b + a );

    }       
});

Aucun commentaire:

Enregistrer un commentaire