Home > database >  Get input radio value by jquery
Get input radio value by jquery

Time:03-05

I need to get the radio input value from the following code:

 <label >
                       <input type="radio" id="TipoPessoa" name="TipoPessoa" value="1" checked >
                        <label for="TipoPessoa" >Física</label>
                        </label>
                        <br>
                    <label >
                       <input type="radio" id="TipoPessoa" name="TipoPessoa" value="2" >
                        <label for="TipoPessoa" >Jurídica</label>
                    </label>

And I'm validating like this, and sending it to the server via Ajax:

  var data =  ({
                Ativo: $("input[Id='Ativo']:checked").val(),
                Nome: $("input[name='Nome']").val(),
                CodigoCliente: $("input[name='CodigoCliente']").val(),
                DataNascimento: moment($("input[name='DataNascimento']").val(), 'dd/MM/yyyy').toJSON(),
                Email: $("input[name='Email']").val(),
                CpfCnpj: $("input[name='CpfCnpj']").val(),
                Celular: $("input[name='Celular']").val(),
                Telefone: $("input[name='Telefone']").val(),
                TipoPessoa: $("input[name='TipoPessoa']:checked").val(). toString(),
                OrigemPessoa: $("input[Id='OrigemPessoa']:checked").val(),
                InscricaoEstadual: $("input[Id='IE']:checked").val(),
                ReceberEmail: $("input[name='ReceberEmail']:checked").val(),
                Sexo: $("input[Id='Sexo']:checked").val(),

$.ajax({
                url: 'api/cliente',
                type: "POST",
                data: JSON.stringify(data),
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(JSON.stringify(data));
                },
                "error": function (result) {
                    var response = result.responseText;
                    alert('Erro: '   response);
                },

            });
    
    

I'm getting the following error:

TipoPessoa":["The JSON value could not be converted to BitCaseiro.Multi.Web.Models.Clientes.TipoPessoa. Path: $.TipoPessoa | LineNumber: 0 | BytePositionInLine: 124."]}}

CodePudding user response:

Well simply remove the id property, id can not be placed in both inputs. Just keep the name the same.

A Question: is it a form? if so why don't you simply serialize the form using jquery instead of getting the values one by one?

 <form ....>
   <label >
   <input type="radio" id="TipoPessoa" name="TipoPessoa" value="1" checked 
   >
   <label for="TipoPessoa" >Física</label></label>
                    <br><label >
                   <input type="radio" name="TipoPessoa" 
    value="2" ><label for="TipoPessoa" >Jurídica</label>
                </label>
 ......
 </form>

then using jquery

var data = $("form").serialize();

CodePudding user response:

This is the draft of my answer which seems to indicate that the issue is not client-side but server-side instead.

This example;

  • made the ids of the radio buttons unique
  • cleaned up the data object initialization (minimally)
  • removed the ajax
  • put the call and serializtion into a button click event to testing.

Looks like the object property TipoPessoa that you are sending is a string but likely the api endpoint is looking for a complex object of some kind.

$(() => {
  // sample button click event to gather and stringify the input data //
  $("button").on("click", () => {
    var data = ({
      Ativo: $("input[Id='Ativo']:checked").val(),
      Nome: $("input[name='Nome']").val(),
      CodigoCliente: $("input[name='CodigoCliente']").val(),
      DataNascimento: moment($("input[name='DataNascimento']").val(), 'dd/MM/yyyy').toJSON(),
      Email: $("input[name='Email']").val(),
      CpfCnpj: $("input[name='CpfCnpj']").val(),
      Celular: $("input[name='Celular']").val(),
      Telefone: $("input[name='Telefone']").val(),
      TipoPessoa: $("input[name='TipoPessoa']:checked").val(),
      OrigemPessoa: $("input[Id='OrigemPessoa']:checked").val(),
      InscricaoEstadual: $("input[Id='IE']:checked").val(),
      ReceberEmail: $("input[name='ReceberEmail']:checked").val(),
      Sexo: $("input[Id='Sexo']:checked").val()
    });
    console.log(JSON.stringify(data));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label >
                       <input type="radio" id="TipoPessoa_1" name="TipoPessoa" value="1" checked >
                        <label for="TipoPessoa" >Física</label>
</label>
<br>
<label >
                       <input type="radio" id="TipoPessoa_2" name="TipoPessoa" value="2" >
                        <label for="TipoPessoa" >Jurídica</label>
</label>
<div><button>Test</button></div>

  • Related