How to leave empty textbox after an Ajax request via Post?

Asked

Viewed 612 times

5

I have a registration application in . net MVC and I am using Ajax to send the contents of the Forms For my Action that registers, when save the value of the fields, in my view the values are still visible in the fields not leaving blank ,as would be the default. Please check my code:

    <div id="endereco">
    @Html.Label("Endereco: ")
    @Html.TextBoxFor(e => e.DescricaoEndereco, new { maxlength = "50", id = "Endereco", name = "Endereco" })

    <br />
    @Html.Label("Número: ")
    @Html.TextBoxFor(e => e.Numero, new { maxlength = "50", id = "Numero" })
    <br />
    @Html.Label("Complemento: ")
    @Html.TextBoxFor(e => e.Complemento, new { maxlength = "50", id = "Complemento" })
    <br />
    @Html.Label("Bairro: ")
    @Html.TextBoxFor(e => e.Bairro, new { maxlength = "50", id = "Bairro", name = "Bairro" })
    <br />
    @Html.Label("Cidade: ")
    @Html.TextBoxFor(e => e.Cidade, new { maxlength = "40", id = "Cidade", name = "Cidade" })
    <br />
    @Html.Label("UF: ")
    @Html.DropDownListFor(e => e.UF, Model.UFList, new { id = "UF",name="UF" })
    <br />

<input type="button" value="Adicionar Endereco" onclick="adicionarEndereco()"/>
        <\div>
    function adicionarEndereco() {
    var codigoPessoa = $("#Pessoa").val();
    var cep = $("#Cep").val();
    var endereco = $("#Endereco").val();
    var numero = $("#Numero").val();
    var complemento = $("#Complemento").val();
    var bairro = $("#Bairro").val();
    var cidade = $("#Cidade").val();
    //var temp = document.getElementById("UF");
    var uf = $("#UF").val();  

    $.ajax(
        {
            type: "POST",
            url: "/Master/CadastrarEndereco",
            data: {
                CodigoPessoa:codigoPessoa,
                Cep: cep,
                DescricaoEndereco:endereco,
                Numero: numero,
                Complemento: complemento,
                Bairro: bairro,
                Cidade: cidade,
                UF : uf,


            },
            success: function (data) {

                $("#endereco").html(data);

            },


        });
}
          //Controller

                   [HttpPost]
    public PartialViewResult CadastrarEndereco(SuperViewModel enderecoVM)
    {
        if (ModelState.IsValid)
        {
            var endereco = Extentions.MapearEndereco(enderecoVM);
            EnderecoRepositorio.Cadastrar(endereco);
            EnderecoRepositorio.Commit();
        }
        var superVM = new SuperViewModel();
        superVM.UFList = Extentions.ObterUF();
        superVM.Enderecos = EnderecoRepositorio.ObterEnderecoPorPessoa(enderecoVM.CodigoPessoa);
        return PartialView("_EnderecoFields", superVM);
    }

3 answers

4

You can do a function to clear the form and call it on success ajax:

function limpaForm(){
    $("#Pessoa").val('');
    $("#Cep").val('');
    $("#Endereco").val('');
    $("#Numero").val('');
    $("#Complemento").val('');
    $("#Bairro").val('');
    $("#Cidade").val('');
    // Como UF é um dropdown, você precisa usar o change para ele mudar a view
    // Pelo que vi no código UF é seu id "default"
    $("#UF").val('UF').change();
}

Change the success for:

success: function (data) {
    $("#endereco").html(data);
    limpaForm();
},

4

You can add this to the callback success of your ajax request:

$('#Pessoa,#Cep,#Endereco,#Numero,#Complemento,#Bairro,#Cidade,#UF').val('');

An ideal solution would be for you to place these fields within a form. Facilitates both when sending and when cleaning the fields.

Ex.:

<form id="form_endereco" action="" method="post">
    @Html.Label("Endereco: ")
    @Html.TextBoxFor(e => e.DescricaoEndereco, new { maxlength = "50", id = "Endereco", name = "Endereco" })

    <br />
    @Html.Label("Número: ")
    @Html.TextBoxFor(e => e.Numero, new { maxlength = "50", id = "Numero" })
    <br />
    @Html.Label("Complemento: ")
    @Html.TextBoxFor(e => e.Complemento, new { maxlength = "50", id = "Complemento" })
    <br />
    @Html.Label("Bairro: ")
    @Html.TextBoxFor(e => e.Bairro, new { maxlength = "50", id = "Bairro", name = "Bairro" })
    <br />
    @Html.Label("Cidade: ")
    @Html.TextBoxFor(e => e.Cidade, new { maxlength = "40", id = "Cidade", name = "Cidade" })
    <br />
    @Html.Label("UF: ")
    @Html.DropDownListFor(e => e.UF, Model.UFList, new { id = "UF",name="UF" })
    <br />
</form>

And in your job adicionarEndereco():

function adicionarEndereco() {
    // pega automaticamente todos os valores preenchidos no form 
    // sem a necessidade de declarar uma variável pra cada um
    var dados = $('#form_endereco').serialize();

    $.ajax(
        {
            type: "POST",
            url: "/Master/CadastrarEndereco",
            data: dados,
            success: function (data) {

                $("#endereco").html(data);

                // limpa todos os campos do form
                $('#form_endereco :input').val('');

            },
        });

        return false;
}
  • But what if he has one select or textarea also on the form? :input would not work.

  • 1

    @Wallacemaxters The selector :input selects all elements of the types input, textarea, select and button within the form. Documentation

  • Ah, yes! it’s true. It’s not input and yes :input! Confudi! Deserved +1, Srsrsrsrsrsrs

2

Luiz Henrique’s answer is fine, but whenever we can simplify something you’ll make it better

You can do this in a row:

$('#meu-form').get(0).reset();

That way, if you add a input the more in your form, you will not need to add it in a function.

Where the get(0) takes the element of DOM stored in the Array generated by jQuery and the reset is the native javascript method for resetting forms.

It is worth remembering that reset returns the form to the initial state, it does not properly clear a form. If in incial state an input has a value equal to 5, when reset it will return to the value equal to 5.

You can do so in your successes:

success: function (data) {

        $('#meu-form').get(0).reset();
    },
  • If you need a more peaceful way to work with ajax forms, you can use the plugin I made to facilitate filling and obtaining data. https://github.com/wallacemaxters/jquery-object-form

  • Thank you guys I got it!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.