Get value from a radio in jquery cakephp

Asked

Viewed 180 times

2

In my code I have a radio and would like to get the option selected in a variable in my jquery function.

Button input:

    <?php
        echo $this->Form->input('attendance_status_id', array(
          'type' => 'radio',
          'options' => $attendance_statuses,
          'div' => array('id' => 'attendance-statuses', 'class' => 'attendance_statuses'),
          'legend' => '',
          'label' => true
          ));
          ?>

Script in which I want to receive it:

    $("#attendance-statuses").change(function(){
  var obs = $('input[name = attendance_status_id]:checked').serialize();
  console.log(obs);
  $.ajax({
    type: 'post',
    data: 
    {obs, 
    obsEntity: 1
    },
    url: "<?php echo Router::url('/observations/observation_options'); ?>",
    success:function(dados){
      dados = JSON.parse(dados);
      var $el = $("#obs-select");
      $('#obs-select option:gt(0)').remove();
      $.each(dados, function(value,key) {
        $el.append($("<option></option>")
           .attr("value", value).text(key));
      });
    }
  });
});

1 answer

1


Note that this object is badly formatted:

data: {
    obs, 
    obsEntity: 1
},

should be

data: {
    obs: obs,   // <-- faltava-te "valor" dessa "chave" do par chave/valor
    obsEntity: 1
},

Since the radio Buttons can only be chosen one at a time you could also have:

// usei ".val()" em vez de ".serialize()"
var obs = $('input[name = attendance_status_id]:checked').val(); 

and in AJAX:

data: {
    attendance_status_id: obs, 
    obsEntity: 1
},

but it’s a matter of preference and I don’t even know how you’re doing in PHP to receive this POST.

  • 2

    It worked here, thank you

Browser other questions tagged

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