locked
Clear All controls for the form? RRS feed

  • Question

  • User1096912014 posted

    Hi everybody,

    I have this code which I don't really like:

    function clearAll() {
        $('#fntype').val('');
        $('#Number').val('');
        $('#Name').val('');
        $('#Contact1').val('');
    
    };

    Assuming that form name is #sForm, how can I re-write the above to clear all textboxes (and multi-line) in that form?

    And also, how can I assign values to all appropriate controls using the model?

    Thanks a lot in advance.

    Monday, October 15, 2012 1:42 PM

Answers

  • User1779161005 posted

    Built into html:

    <button type=reset>Clear</button>

    or

    <input type=reset value="Clear" />

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 1:43 PM
  • User1779161005 posted

    Ok, so since the button has to do more than the normal reset then it might just be easier for your clear function to look like this:

    function clearForm(){

        $("#theFormID input").val("");

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:02 PM
  • User1779161005 posted

    When the button is clicked, they don't pass that sort of param. But you could do something like:

    function clearButtonClick(){
         $(this).closest("form").find("input").val("");
    }

    Assuming you've used this function as the click callback function, the "this" is the button, the $(this) wraps is in jQuery, closest looks to the closest parent that's a "form" element, and then for that form element we find all children "input" elements and then set all their values to "".

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:14 PM
  • User1779161005 posted

    One more question - using input it also cleared both of my buttons! How can I exclude buttons from the above?

    Use a different selector, like ":text" -- there are lots to choose from:

    http://api.jquery.com/category/selectors/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:29 PM
  • User1779161005 posted

    Do you see how can I do it this way? That form above is saved right now as a partial view. How can I invoke that form?

    Usually one registers events from code, not from markup:

    $(function(){
        $(".clearButton".click(function(){
           // do your clear stuff here
        });
    });

    so just put a CSS class on the buttons you want to do this "clear" behavior.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:31 PM
  • User1779161005 posted

    You could wire up the buttons after the dialog is created:

    $("#grid").dialog(...);
    $("#grid").find(".clearButton").click(...);

    Or you could even use the delegation feature in jQuery:

    $("body").on("click", ".clearButton", function() { ... });

    This way you register the click handler (via on("click", ".clearButton")) on a container element and this works via the event bubbling mechanism in the DOM.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 3:02 PM
  • User1779161005 posted

    Also, what is the best way to make this part:

    ...

    to be side by side - e.g. Contact1 info and next to it Contact2 info?

    CSS is for styling, so that's what I'd use.

    Funny, but the form seems to work OK, except that I need to figure out how to assign values correctly in the Edit - can you help me here a bit?

    ...

    So, I am assigning values from the selected row. However, 

    1. I need more columns (and I am not showing them in a grid)

    2. I don't want to list every input control, I somehow want to assign the values automatically. Do you see my problem here?

    1) I don't know the grid component you're using, so I don't know it's features/limitations. I guess you need to have it maintain more data than it's showing? Maybe use some hidden fields?

    2) Again, I don't totally see the problem but I'm not knee-deep in it like you are. Perhaps some meta-data on the tags to help with the mapping. At some point you need to build mapping from one to another, so if not something explicit then some convention... maybe the <td> index maps to the <input> index? Feels brittle, though.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 6:32 PM

All replies

  • User1779161005 posted

    Built into html:

    <button type=reset>Clear</button>

    or

    <input type=reset value="Clear" />

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 1:43 PM
  • User1096912014 posted

    Thanks, let me try that, but it also needs to close the form and also I still need it as a function as well. I can show you a bit of code, so you may see if I need it.

    Here is my view:

    @model CardNumbers.Objects.Client
    
    @{
        ViewBag.Title = "Client";
    }
    
     <form id="frmClientsSearch">
            
            <label for="clientNo">Client No: </label>
            <input type="number" name="searchClientNo" class="numericOnly" /><br />
            <label for="clientName">Client Name: </label>
            <input type =  "text" size =25 value ="Please enter the search value"
                name ="searchClientName" />
            
           <input type="button" id="btnClientsSearch" value ="Find / Refresh" />      
    </form>
    <div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;" id="ClientsResults">
        <table id="flexClients" style="display: none">
        </table>
    </div>
    <div style="display: none">
       <form id="sform">
            <input type="hidden" id="fntype" name="fntype">
            <input type="hidden" id="Id" name="Id">
            <label for="Number">Client No: </label>
            <input type="number" id="Number" name="Number" class="numericOnly" />
            <label for="Name">Client Name: </label>
            <input type="text" size="25" id="Name" name="Name" /><br />
            <label for="Contact11">Contact 1: </label>
            <input type="text" size="25" id="Contact1" name="Contact1" /><br />
            <div class="float-right">
                <input type="button" value="Submit" id="btnSave">
                <input type="button" value="Cancel" id="btnClear" />
            </div>
        </form>
    </div>
    

    So, the sForm is called from the grid to display the data as a new window. I am not yet clear as how to make this form to be the same as the 'Create / Edit' view with all validations built-in.

    So, in the main js file for the application I have the following code:

    function test(com, grid) {
        if (com === 'Delete') {
            var clientName = $('.trSelected td:eq(2)').text();
            if (clientName) //Variable is defined and not empty
            {
                if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?"))
                    return false;
    
                $('#fntype').val('Delete');
                $('#Id').val($('.trSelected td:eq(0)').text());
                $('#Number').val('');
                $('#Name').val('');
                $('#Contact1').val('');
    
                $('.trSelected', grid).each(function () {
                    var id = $(this).attr('id');
                    id = id.substring(id.lastIndexOf('row') + 3);
    
                    addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
                });
    
                clearAll();
            }
        } else if (com === 'Add') {
    
            $("#sform").dialog({
                autoOpen: false,
                show: "blind",
                width: 1000,
                height: 500
            });
            $("#sform").dialog("open");
    
            $('#fntype').val('Add');
            $('#Number').val('');
            $('#Name').val('');
            $('#Contact1').val('');
    
        } else if (com === 'Edit') {
    
            $('.trSelected', grid).each(function () {
    
                $("#sform").dialog({
                    autoOpen: false,
                    show: "blind",
                    width: 1000,
                    height: 500
                });
                $("#sform").dialog("open");
    
                $('#fntype').val('Edit');
                $('#Id').val($('.trSelected td:eq(0)').text());
                $('#Number').val($('.trSelected td:eq(1)').text());
                $('#Name').val($('.trSelected td:eq(2)').text());
                $('#Contact1').val($('.trSelected td:eq(3)').text());
    
            });
    
        }
    }
    
    function clearAll() {
        $('#fntype').val('');
        $('#Number').val('');
        $('#Name').val('');
        $('#Contact1').val('');
    
    };
    
    $(function () {
        $('#btnSave').click(function () {
            addFormData();
            $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
            clearAll();
            $('#sform').dialog('close');
            return false;
        });
    });
    
    $(function () {
        $('#btnClear').click(function () {      
            
            clearAll();
            $('#sform').dialog('close');
            return false;
        });
    });
    
    
    $(function () {
        $('#btnClientsSearch').click(function () {
            addFormData();
            $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
            //$.ajax({
            //    url: $(this).data('url'),
            //    type: 'GET',
            //    cache: false,
            //    success: function (result) {
            //        $('#ClientsResults').html(result);
            //    }
            //});
            return;//false;
        });
    });
    

    I am looking into simplifying this code and also making it more generic, so I can use it for another grid.

    Appreciate your input.


    Monday, October 15, 2012 1:57 PM
  • User1779161005 posted

    Ok, so since the button has to do more than the normal reset then it might just be easier for your clear function to look like this:

    function clearForm(){

        $("#theFormID input").val("");

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:02 PM
  • User1096912014 posted

    What if I want to pass the name of the form as a parameter, e.g.

    function clearForm(string formName){

    }

    ?

    Monday, October 15, 2012 2:05 PM
  • User1096912014 posted

    One more question - using input it also cleared both of my buttons! How can I exclude buttons from the above?

    The form currently is:

    <div style="display: none">
       <form id="sform">
            <input type="hidden" id="fntype" name="fntype">
            <input type="hidden" id="Id" name="Id">
            <label for="Number">Client No: </label>
            <input type="number" id="Number" name="Number" class="numericOnly" />
            <label for="Name">Client Name: </label>
            <input type="text" size="25" id="Name" name="Name" /><br />
            <label for="Contact11">Contact 1: </label>
            <input type="text" size="25" id="Contact1" name="Contact1" /><br />
            <div class="float-right">
                <input type="button" value="Submit" id="btnSave">
                <input type="button" value="Cancel" id="btnClear" />
            </div>
        </form>
    </div>
    



    Monday, October 15, 2012 2:12 PM
  • User1779161005 posted

    When the button is clicked, they don't pass that sort of param. But you could do something like:

    function clearButtonClick(){
         $(this).closest("form").find("input").val("");
    }

    Assuming you've used this function as the click callback function, the "this" is the button, the $(this) wraps is in jQuery, closest looks to the closest parent that's a "form" element, and then for that form element we find all children "input" elements and then set all their values to "".

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:14 PM
  • User1096912014 posted

    Thanks again for your help. In the meantime, I slightly changed the above view to use button instead of input type="button" and it seems to work OK in Google Chrome - I am going to run a quick test in FireFox and IE:

    <div style="display: none">
       <form id="sform">
            <input type="hidden" id="fntype" name="fntype">
            <input type="hidden" id="Id" name="Id">
            <label for="Number">Client No: </label>
            <input type="number" id="Number" name="Number" class="numericOnly" />
            <label for="Name">Client Name: </label>
            <input type="text" size="25" id="Name" name="Name" /><br />
            <label for="Contact11">Contact 1: </label>
            <input type="text" size="25" id="Contact1" name="Contact1" /><br />
            <div class="float-right">
                <button type="Submit" id="btnSave">Submit</button>
                <button type=reset id="btnCancel">Cancel</button>
            </div>
        </form>
    </div>
    

    My question now is - I want to make this form to be more like this:

    @model CardNumbers.Objects.Client
    <div class="editor-label">
                @Html.LabelFor(model => model.Number)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Number)
                @Html.ValidationMessageFor(model => model.Number)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Address)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Address)
                @Html.ValidationMessageFor(model => model.Address)
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Contact1)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Contact1)
                @Html.ValidationMessageFor(model => model.Contact1)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Email1)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Email1)
                @Html.ValidationMessageFor(model => model.Email1)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Phone1)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Phone1)
                @Html.ValidationMessageFor(model => model.Phone1)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Ext1)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Ext1)
                @Html.ValidationMessageFor(model => model.Ext1)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Contact2)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Contact2)
                @Html.ValidationMessageFor(model => model.Contact2)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Email2)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Email2)
                @Html.ValidationMessageFor(model => model.Email2)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Phone2)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Phone2)
                @Html.ValidationMessageFor(model => model.Phone2)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Ext2)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Ext2)
                @Html.ValidationMessageFor(model => model.Ext2)
            </div>   
    

    Do you see how can I do it this way? That form above is saved right now as a partial view. How can I invoke that form?


    Monday, October 15, 2012 2:22 PM
  • User1779161005 posted

    One more question - using input it also cleared both of my buttons! How can I exclude buttons from the above?

    Use a different selector, like ":text" -- there are lots to choose from:

    http://api.jquery.com/category/selectors/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:29 PM
  • User1779161005 posted

    Do you see how can I do it this way? That form above is saved right now as a partial view. How can I invoke that form?

    Usually one registers events from code, not from markup:

    $(function(){
        $(".clearButton".click(function(){
           // do your clear stuff here
        });
    });

    so just put a CSS class on the buttons you want to do this "clear" behavior.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 2:31 PM
  • User1096912014 posted

    Thanks, Brock. So far so good.

    But what about my more complex question? E.g. the flexigrid which instantiates on the fly has the following code to associate Add/Edit/Delete buttons with the action:

    buttons: [
            { name: 'Add', bclass: 'add', onpress: test },
            { name: 'Edit', bclass: 'edit', onpress: test },
            { name: 'Delete', bclass: 'delete', onpress: test },
            { separator: true }
            ],

    and this code in the test method function:

    function test(com, grid) {
        if (com === 'Delete') {
            var clientName = $('.trSelected td:eq(2)').text();
            if (clientName) //Variable is defined and not empty
            {
                if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?"))
                    return false;
    
                $('#fntype').val('Delete');
                $('#Id').val($('.trSelected td:eq(0)').text());
                $('#Number').val('');
                $('#Name').val('');
                $('#Contact1').val('');
    
                $('.trSelected', grid).each(function () {
                    var id = $(this).attr('id');
                    id = id.substring(id.lastIndexOf('row') + 3);
    
                    addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
                });
    
                clearForm();
            }
        } else if (com === 'Add') {
    
            $("#sform").dialog({
                autoOpen: false,
                show: "blind",
                width: 1000,
                height: 500
            });
            $("#sform").dialog("open");
    
            $('#fntype').val('Add');
            $('#Number').val('');
            $('#Name').val('');
            $('#Contact1').val('');
    
        } else if (com === 'Edit') {
    
            $('.trSelected', grid).each(function () {
    
                $("#sform").dialog({
                    autoOpen: false,
                    show: "blind",
                    width: 1000,
                    height: 500
                });
                $("#sform").dialog("open");
    
                $('#fntype').val('Edit');
                $('#Id').val($('.trSelected td:eq(0)').text());
                $('#Number').val($('.trSelected td:eq(1)').text());
                $('#Name').val($('.trSelected td:eq(2)').text());
                $('#Contact1').val($('.trSelected td:eq(3)').text());
    
            });
    
        }
    }

    So, my ideas are:

    1. Somehow generalize that code, so I can invoke it from any flexigrid, not just flexClients.

    2. Somehow have my more complex forms here - the ones I create using CREATE/EDIT template for the view. On the other hand, I like that idea of the "modal" form instead of a new page.

    Do you see how can I realize these ideas?

    Thanks a lot again, I learned quite a lot from you so far.


    Monday, October 15, 2012 2:57 PM
  • User1779161005 posted

    You could wire up the buttons after the dialog is created:

    $("#grid").dialog(...);
    $("#grid").find(".clearButton").click(...);

    Or you could even use the delegation feature in jQuery:

    $("body").on("click", ".clearButton", function() { ... });

    This way you register the click handler (via on("click", ".clearButton")) on a container element and this works via the event bubbling mechanism in the DOM.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 3:02 PM
  • User1096912014 posted

    Funny, but the form seems to work OK, except that I need to figure out how to assign values correctly in the Edit - can you help me here a bit?

    Also, what is the best way to make this part:

    <div class="editor-label">
        @Html.LabelFor(model => model.Contact1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Contact1)
        @Html.ValidationMessageFor(model => model.Contact1)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Email1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email1)
        @Html.ValidationMessageFor(model => model.Email1)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Phone1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Phone1)
        @Html.ValidationMessageFor(model => model.Phone1)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Ext1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Ext1)
        @Html.ValidationMessageFor(model => model.Ext1)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Contact2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Contact2)
        @Html.ValidationMessageFor(model => model.Contact2)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Email2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email2)
        @Html.ValidationMessageFor(model => model.Email2)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Phone2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Phone2)
        @Html.ValidationMessageFor(model => model.Phone2)
    </div>
    
    <div class="editor-label">
        @Html.LabelFor(model => model.Ext2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Ext2)
        @Html.ValidationMessageFor(model => model.Ext2)
    </div>
    

    to be side by side - e.g. Contact1 info and next to it Contact2 info?

     ------------------

    For the Edit here is the problem:

     $("#flexClients").flexigrid({
            url: '/Client/Client/',
            dataType: 'json',
            colModel: [
            { display: 'Client Id', name: 'Id', width: 100, sortable: true, align: 'center', hide: true},
            { display: 'Client #', name: 'Number', width: 100, sortable: true, align: 'center' },
            { display: 'Name', name: 'Name', width: 350, sortable: true, align: 'center' },
            { display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' },
            ],
            buttons: [
            { name: 'Add', bclass: 'add', onpress: test },
            { name: 'Edit', bclass: 'edit', onpress: test },
            { name: 'Delete', bclass: 'delete', onpress: test },
            { separator: true }

    and the form has more controls than defined in JSON for the grid.

    The current Edit button code is:

    else if (com === 'Edit') {
    
            $('.trSelected', grid).each(function () {
    
                $("#sform").dialog({
                    autoOpen: false,
                    show: "blind",
                    width: 1000,
                    height: 900
                });
                $("#sform").dialog("open");
    
                $('#fntype').val('Edit');
                $('#Id').val($('.trSelected td:eq(0)').text());
                $('#Number').val($('.trSelected td:eq(1)').text());
                $('#Name').val($('.trSelected td:eq(2)').text());
                $('#Contact1').val($('.trSelected td:eq(3)').text());
    
            });

    So, I am assigning values from the selected row. However, 

    1. I need more columns (and I am not showing them in a grid)

    2. I don't want to list every input control, I somehow want to assign the values automatically. Do you see my problem here?

    What do you think?



    Monday, October 15, 2012 4:51 PM
  • User1779161005 posted

    Also, what is the best way to make this part:

    ...

    to be side by side - e.g. Contact1 info and next to it Contact2 info?

    CSS is for styling, so that's what I'd use.

    Funny, but the form seems to work OK, except that I need to figure out how to assign values correctly in the Edit - can you help me here a bit?

    ...

    So, I am assigning values from the selected row. However, 

    1. I need more columns (and I am not showing them in a grid)

    2. I don't want to list every input control, I somehow want to assign the values automatically. Do you see my problem here?

    1) I don't know the grid component you're using, so I don't know it's features/limitations. I guess you need to have it maintain more data than it's showing? Maybe use some hidden fields?

    2) Again, I don't totally see the problem but I'm not knee-deep in it like you are. Perhaps some meta-data on the tags to help with the mapping. At some point you need to build mapping from one to another, so if not something explicit then some convention... maybe the <td> index maps to the <input> index? Feels brittle, though.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 15, 2012 6:32 PM
  • User1096912014 posted

    Yes, I think I will need to pass all columns and hide the rest. There is an ability to "unhide" the columns by the grid, but it doesn't seem to work OK in Google Chrome and I don't think many users will start unhiding the columns, so I guess this is the route I'll take.

    I also was able to get side by side with styling, but still need to fiddle with it a bit. I was not doing ASP.NET for a few years, so I have to re-learn lots of stuff (if I ever knew them).

    Monday, October 15, 2012 8:14 PM