0
<?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!

3 Answers 3

1

Something like:

$("select[name='fruits[]']").change(function () {
    var selectedIndex = this.selectedIndex,
        value =  this.value;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.