Eddas
Eddas

Reputation: 77

get html dropdown array in jquery

On my html page, I have a variable number of dropdown boxes, each with the following code:

<select name="gearquan[]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
</select>

If using a regular form submit, it sends as a nested array. I'm trying to convert my forms over to using jquery and ajax. When I had a list of checkboxes I used the following code to get their values:

var gear = new Array();
$("input:checked").each(function() {
    gear.push($(this).val());
});

What would I need to change in that, in order to get the values of the dropdown boxes? (Other than changing gear to gearquan)

Upvotes: 1

Views: 44

Answers (1)

CodeGodie
CodeGodie

Reputation: 12132

It seems like you are trying to manually build arrays to send to your PHP through AJAX, you don't need to do all that. When using jQuery and AJAX all you need to do is use .submit() to handle your submit event and .serialize() to get all your current form's data to send thorough AJAX as such:

$('form').submit(function(e){
    e.preventDefault();
    var postdata = $(this).serialize();
    $.ajax({
        url: 'file.php',
        type: 'post',
        data: postdata,
        success: function(response){
           console.log(response);
        }
    });
});

Upvotes: 1

Related Questions