Saturday, March 22, 2014

Concatenate inputs from multiple TextBox and assign to one Using Jquery in ASP .net

gautam-gupta-concatenate-inputs-asp-.net-jquery
In this example I am going to show how to get inputs from different input fields (TextBox) on keyup event using client side script, Jquery and Concatenate them using separators in between using tertiary Operator then assign them to another input field.

Here is the input Fields we are going to get text from on keyup event from txtCo1 to txtCo5 and going to assign the concatenated value to txtCode.

  <tr>
            <td>
                <asp:Label ID="LblCode" runat="server" Text="Code"></asp:Label>
            </td>

            <td>
                <asp:TextBox Width="20px" ID="txtCo1" CssClass="co1" runat="server" MaxLength="2"></asp:TextBox>-
                <asp:TextBox Width="20px" ID="txtCo2" runat="server" CssClass="co2" MaxLength="2"></asp:TextBox>-
                <asp:TextBox ID="txtCo3" Width="20px" runat="server" CssClass="co3" MaxLength="1"></asp:TextBox>-
                <asp:TextBox ID="txtCo4" Width="20px" runat="server" CssClass="co4" MaxLength="2"></asp:TextBox>-
                <asp:TextBox ID="txtCo5" Width="20px" runat="server" CssClass="co5" MaxLength="2"></asp:TextBox>
            </td>
            <td></td>

            <td>
                <asp:TextBox class="form-control input-sm " ID="txtCode" CssClass="code" runat="server"></asp:TextBox>
            </td>
        </tr>
Here is the Jquery Code to Accomplish this Operation Client Side.
 <script type="text/javascript">
            $(function () {

                $(
            '.co1, .co2, .co3, .co4, .co5').keyup(function () {
                $('.code').val(
                    $('.co1').val() + ($('.co2').val().length > 0 ? '-' + $('.co2').val() : '')
                                    + ($('.co3').val().length > 0 ? '-' + $('.co3').val() : '')
                                    + ($('.co4').val().length > 0 ? '-' + $('.co4').val() : '')
                                    + ($('.co5').val().length > 0 ? '-' + $('.co5').val() : '')
                    );
            }

            );

            }
                );
        </script>

Here class of each input field are identified and assigned keyup event to each in the following code
$('.co1, .co2, .co3, .co4, .co5').keyup(function () {......});

now the values of each input field are assigned using .val() function to Code using following code
$('.code').val(....);

to add dash only with value having length>0 here is the tertiary operator
..  + ($('.co3').val().length > 0 ? '-' + $('.co3').val() : '')

Thats all, using this we can accomplish the Concatenation of text values of multiple input fields or TextBox and assign them to another input field using conditional dashes using tertiary Operator.