ahnkee
ahnkee

Reputation: 145

jQuery - get value from a select when there are several

I am dynamically inserting many selects on to my page depending on user inputs. The select lists are identical and share similar names.

When the user chooses an option, I want to grab that value. (In the end what I'm trying to accomplish is to disable the chosen value from all other lists, but re-enable it if the value is changed. But one step at a time)

I am assuming that I will need to use $(this) but I apparently do not know how to get the values from the second, third lists, and so on.

The HTML would be something like this:

<select name="category[first]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select name="category[second]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

** Many more lists with the same naming convention

As for my jQuery, I was trying something like this:

$('body').on('change', $('select[name^="category"]', function(){
    alert( $(this).find('option:selected').val() );
});

But that only gives me the value from the first select, and not from any subsequent ones. My understanding is that I have to use $('body') or $('document') since they are dynamically created elements.

Any help would be appreciated, thank you.

Upvotes: 0

Views: 53

Answers (2)

CodeGodie
CodeGodie

Reputation: 12132

This is how I would do it: DEMO FIDDLE

 $('body').on('change', 'select', function () {
     var selected_value = $(this).val();
     $('select option').each(function(){
         if(this.value == selected_value){
             $(this).prop('disabled', true);
         } else {
             $(this).prop('disabled', false);
         }
     });
 });

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

Remove the $( before the selector. The selector needs to be a string, not jQuery object

$('body').on('change', 'select[name^="category"]', function(){
    console.log( $(this).find('option:selected').val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select name="category[first]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<select name="category[second]">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Upvotes: 1

Related Questions