alkhader
alkhader

Reputation: 998

Passing selected options as an array using ajax

I have a contact list as below:

<div class="contacts_list_data_contacts" id="contactlist">
<div class="contacts_checkbox_01"><input name="contact_id[]" id="contact_id" type="checkbox"  value="28383" style="margin-top:0px ; margin-left:-3px;" /></div>
<div class="contacts_firstname_01_contacts">Michael</div>                                 
<div class="ncontacts_mobile_nmbr_01">+44515665544</div>
</div>

<div class="contacts_list_data_contacts" id="contactlist">
<div class="contacts_checkbox_01"><input name="contact_id[]" id="contact_id" type="checkbox"  value="28383" style="margin-top:0px ; margin-left:-3px;" /></div>
<div class="contacts_firstname_01_contacts">Katherine</div>                                 
<div class="ncontacts_mobile_nmbr_01">+30589746621</div>
</div>

It looks like that:

Firstname     MobileNumber
===========================
Michael       +44515665544
Katherine     +30589746621          

I am using ajax request to delete a contact

contact_id=document.getElementById('contact_id_ajax').value;
    xmlHttp.open("POST","?action=ajaxcontact&todo=DeleteContact&contact_id=" +contact_id ,true);

Using the below function I am able to get ONLY one contact at once by put a checkbox. I don't know how to pass all of the contacts when I select all the contacts and pass them to the ajax request.

<Script>
var field;
        function get_contact(field)
        {
            for (i = 0; i < field.length; i++)

            if(field[i].checked)
             document.getElementById("contact_id_ajax").value=field[i].value;
        }
</Script>

Thank you,

Upvotes: 0

Views: 266

Answers (1)

Jibi Abraham
Jibi Abraham

Reputation: 4696

First things, first. You have a lot places where you use the same IDs for elements. This is very bad practice indeed. IF you want a way to identify a collection of similar items, use classes (you already have - just get rid of the ids or get unique ones).

Now, if you add a class to your checkboxes like so -

<input name="contact_id[]" class="contact_id" type="checkbox"  value="28383" style="margin-top:0px ; margin-left:-3px;" />

Then in your getContacts function, you can skip the argument and go with -

function getContacts(){
    var contacts = document.getElementByClassName('contact_id'), ids = [];
    for (var i = 0; i < contacts.length; i += 1){
        if (contacts[i].checked)
             ids.push(contacts[i].value);
    }
    return ids;
}

Now, when you want the contacts list -

var contacts = getContacts(); //array of contact ids
//This array can now be used in your ajax request

Upvotes: 1

Related Questions