Generic function to clear all Label, TextBox and HiddenField of Form using jQuery

Last Reply one year ago By Mudassar

Posted one year ago

I need a method similar to C# for jQuery.

Please provide the snippet.

Attached is the code for C# :

    public static void Clear(params object[] boxes)
    {
        foreach (var box in boxes)
        {
            if (box != null && box is TextBox)
            {
                (box as TextBox).Text = string.Empty;
            }
            else if (box != null && box is Label)
            {
                (box as Label).Text = string.Empty;
            }
            else if (box != null && box is HiddenField)
            {
                (box as HiddenField).Value = string.Empty;
            }
        }
    }

and it is called like this :

Clear(Textbox1,Label1);

thanks.

Posted one year ago Modified on one year ago

Check this

<div class = "form">
    <input type="text" id = "txtName" value = "Mudassar" class = "Element" />
    <span id="lblName" class = "Element">Mudassar</span>
    <input type="hidden" id = "hfName" value = "Mudassar" class = "Element" />
</div>
    <input type="button" id = "btn" value = "Clear" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            var elements = $(".Element");
            ClearElement(elements);
        });
    });
    function ClearElement(elements) {
        $(elements).each(function () {
            if (this.tagName == "SPAN") {
                $(this).html('');
            }
            if (this.tagName == "INPUT") {
                $(this).val('');
            }
        });
    }
</script>

Demo