bart2puck
bart2puck

Reputation: 2522

adding items to jquery array

I have a form that has an action dropdown and a series of checkboxs that have ids, i want to grab all the checkboxes that are checked, and the action chosen and send them via ajax to another page. current attempt is an array, what else can i try?

<select name='action' id='action'>
    <option value=''></option>
    <option value='reassign'>Reassign</option>
    <option value='merge'>Merge</option>
    <option value='move'>Move</option>
</select>

$('select').on('change',$('#action'),function(){
    data = [];
    $.each($('input:checkbox'),function(e,i){
        if($(this).is(':checked')){
            data[e] = $(this).attr('id');
        }
    });
    data.add = $(this).val();
    $.ajax({
        type:"POST",
        data:{data:data},
        url:"bulkChange.php",
        success: function(result){
            alert(result);
        }
    });
});

Currently, I do not see the action added to the array. print_r($_POST) on bulkChange.php shows:

[data] => Array
    (
        [0] => c_32481
        [1] => c_32477
        [2] => 
        [3] => 
        [4] => 
        [5] => c_32308
    )

i would like to see:

[data] => Array
    (
        [0] => c_32481
        [1] => c_32477
        [2] => 
        [3] => 
        [4] => 
        [5] => c_32308
        [6] => merge
    )

Upvotes: 0

Views: 48

Answers (3)

Vijay
Vijay

Reputation: 431

Try this instead of using

data.add = $(this).val();

$('select').on('change',$('#action'),function(){
    data = [];
    $.each($('input:checkbox'),function(e,i){
        if($(this).is(':checked')){
            data[e] = $(this).attr('id');
        }
    });
    //array push
    data.push($(this).val());
  
    $.ajax({
        type:"POST",
        data:{data:data},
        url:"bulkChange.php",
        success: function(result){
            alert(result);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<select name='action' id='action'>
    <option value=''></option>
    <option value='reassign'>Reassign</option>
    <option value='merge'>Merge</option>
    <option value='move'>Move</option>
</select>

Upvotes: 0

callback
callback

Reputation: 4122

In your code, instead of using

data.add = $(this).val();

use data.push($(this).val());

That should do.

Upvotes: 1

Soronbe
Soronbe

Reputation: 926

$('select').on('change',$('#action'),function(){
                    data = [];
                    $.each($(this).find('option'),function(e,i){
                            if($(this).is(':checked')){
                            data[e] = $(this).attr('value');
                            }
                    });
                   console.log(data);
                    });

Does this construct the data array as you'd like it to?

Upvotes: 0

Related Questions