Paengski
Paengski

Reputation: 349

Retrieve index and value of array selectbox

<?php foreach ($fruits as $fruit) { ?>
    <select name="fruits[]">
        <option value="">Apple</option>
        <option value="">Banana</option>
        <option value="">Orange</option>
    </select>
    <input type="text" name="quantity" value="" />
<?php } ?>

<script>
    $("select[input='fruits[]']").change(function () {
         // how to get the fruits array index 
         // how to get the fruits array value
    });
</script>

How to know the specific index and value selected in fruits array selectbox?

Thanks in advance!

Upvotes: 0

Views: 58

Answers (3)

Thirumalai murugan
Thirumalai murugan

Reputation: 5916

<select name="fruits[]" id="fruit" onchange="calc()">
    <option value="">Apple</option>
    <option value="">Banana</option>
    <option value="">Orange</option>
</select>
<input type="text" name="quantity" value="" />
<script>
function calc()
{
    alert($("#fruit").prop("selectedIndex"));

}
</script>

Demo

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

Firstly the selector should be select[name="fruits[]"]. Then you can use selectedIndex on the DOM element. Try this:

$("select[name='fruits[]']").change(function () {
     console.log(this.selectedIndex);
});

Or for a pure jQuery method, use option:selected:

$("select[name='fruits[]']").change(function () {
     console.log($('option:selected', this).index());
});

Upvotes: 1

Niels
Niels

Reputation: 49929

Something like:

$("select[name='fruits[]']").change(function () {
    var selectedIndex = this.selectedIndex,
        value =  this.value;
});

Upvotes: 1

Related Questions