0

I've created a "global" ajax-modal-function that sends ajax-requests with values stored in data-array at the parent #modal-content.

That's how a HTML field looks like (as an example):

<input data-array='data[]' name='gender' type='radio' value='1' /> 
<input data-array="data[]" type="password" name="password" />

That's how I store the data before I use tha $.ajax JQuery function to get all the data of every input field of the current modal:

var data_array = $('#modal-content').find('*[data-array]').map(function(idx, elem) {    
    return elem.value.trim(); 
}).get();

Then the $.ajax function looks like this:

$.ajax({
    type: "POST", url: "ajax_modal.php", dataType: "json",
    data: { 
        data: data_array, 
        data_case: data_case, 
        id: id, 
        uid: uid, 
        dataString: 'modal_save' 
    },
    success: function(data) {

So the array is stored in data_array and it works fine.

But now I have this radio input field or a checkbox. How can I get the value in my array to store its value depending on if the user clicked it or not?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
AlexioVay
  • 4,338
  • 2
  • 31
  • 49
  • any particular reason you cannot use an actual `form.submit`? this seems like a really weird way to parse a form – BillPull Jun 08 '15 at 18:41
  • @BillPull — That would reload the page. The question is asking about Ajax. – Quentin Jun 08 '15 at 18:42
  • A checkbox or radio button has two states, `true` or `false`. If you loop over those elements, you should be good. – DevNebulae Jun 08 '15 at 18:43
  • 4
    but why use the `data-array` field? seems what you want to do is just serialize the form to json http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – BillPull Jun 08 '15 at 18:44
  • It's because this would affect too many other sections of the whole website to be rewritten, because it was coded with this particular `data-array` "method" to send ajax-data in the first place. – AlexioVay Jun 08 '15 at 18:49

1 Answers1

2

Radio buttons and checkboxes have a property checked. You should explicitly check for this, if the input element you are on is of that type.

var data_array = $('#modal-content').find('*[data-array]').map(function(idx, elem) {
   if (elem.type === 'radio' || elem.type === 'checkbox') {
       return elem.checked && elem.value;
   } else {
       return elem.value.trim(); 
   }
}).get();
Nathanael Smith
  • 3,173
  • 1
  • 13
  • 12