简体   繁体   中英

How to send a radio button value via AJAX?

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM