rich dvc rich dvc - 1 month ago 6
jQuery Question

Jquery to append text in textbox from other textboxes in the same Mvc view

I have 3 textboxes on a form in my mvc view, FirstName, LastName, UserName. The UserName needs to be the FirstName + LastName. I tried the following Jquery which will add the letters of the FirstName field to UserName on the FirstName.KeyUp event, but when I add letters from the LastName field to the UserName it overwrites the FirstName letters (actually I only need the 1st letter of the lastName). What is the Jquery for this to "Append" letters and not overwrite? Is KeyUp a good event for this -- maybe LostFocus or something? Or should I use a function that returns a value with the return keyword? What is the Jquery for that approach?

@using (Html.BeginForm()) {

<fieldset>

<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
</fieldset>
}


<script type="text/javascript">

$(function () {

$("#FirstName").keyup(function () {
$("#UserName").val(this.value);
});
$("#LastName").keyup(function () {
$("#UserName").val(this.value);
});

});

</script>

Answer

You can read both the input values(FirstName and LastName) and append it to get the final value and still overwrite the UserName input value.

$(function(){

   $("#FirstName").keyup(function () {            
        $("#UserName").val($(this).val()+ $("#LastName").val());
   });

   $("#LastName").keyup(function () {
         $("#UserName").val( $("#FirstName").val()+$(this).val());
   });

});

If you want to add only the first letter of last name, you can do this

$(function(){

   $("#FirstName").keyup(function () {   
        var lastName = $("#LastName").val();
        if(lastName!=='')
        {
           lastName=lastName.charAt(0);               
        }
        $("#UserName").val($(this).val()+ lastName);
   });

   $("#LastName").keyup(function () {
        var lastName = $(this).val();
        if(lastName!=='')
        {
            lastName=lastName.charAt(0);               
        }
        $("#UserName").val( $("#FirstName").val()+lastName);
   });

});

Here is a working jsfiddle.

Comments