Home > other >  Check Box adding 2 entries to Payload
Check Box adding 2 entries to Payload

Time:06-05

I've the following in ruby file html.erb

<div  id="contractor-group"> 
   <%= f.check_box :contractor, id: 'int_contractor_check'%>
   <label for="contractor">Internal Contractor</label>
</div>

function enableContractor() {
  var type = $('#company-type').val();
  if (type == 'INTERNAL') {
     $('#contractor-group').removeClass('hidden')
     $('#int_contractor_check').prop('checked', false);
  }
  else {
     $('#int_contractor_check').prop('checked', false);
     $('#contractor-group').addClass('hidden')
  }
}

A dropdown change to INTERNAL toggles the checkbox hidden/shown

id: "company-type",
onchange: "enableContractor()",

In the payload I get double contractor entries. Any ideas what I am doing wrong? enter image description here

CodePudding user response:

Nothing wrong here. For checkboxes Rails creates a hidden field with 0 value (you can check it in generated html). It's needed b/c checkbox value is send only when checkbox is checked. So, to avoid having nothing send, when it's not checked, we need this hidden input. When parsing it on the server, Rails will overwrite 0 with the latest value (1) See docs

CodePudding user response:

I stripped down the code to the following and it's working fine now. Using true and false was better to use on server side anyway. Not sure why the server wasn't using the value 1 ever,

Thanks @faron for the link, something I didn't know.

<div  id="contractor-group">
   <%= f.check_box :contractor, { checked: false }, true, false %>
    <b> Internal Contractor </b>
</div>
  • Related