1

I'm looking for guidance on the following scenario:

Context: A page displays a dynamically generated list with X (changes based on the user) number of items, each formatted as follows:

<div class="dashboard_section_item">
    <label for="add_listname_label">Assign to list</label>
    <br/>
    <select name="mod_list" class="mod_list">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
    </select>
</div>

I need to handle the user selection in the dropdown list in JQuery. The problem is the list is repeated x times on the page, so it will only work for the first item displayed.

$(document).ready(function () {
    $(".mod_list").change(function () {
        $.ajax({
            type: 'POST',
            url: 'mod.php',
            data: 'prod_uid=' + $('.prod_uid').val() + '&mod_list=' + $(this).find(':selected').val(),
            dataType: 'json',
            success: function (response) {...
            },
            error: function () {...
            }
        });
        return false;
    });
});

I'm thinking about concatenating a UID to the list name tag like:

<select name="mod_list_34745727" class="mod_list">

but I'm unsure whether there is a better way to do this.

How can I uniquely identify each item list to select its dropdown value?

Cyrille
  • 15
  • 4
  • I'm not entirely sure what you're asking. Are you having issues handling the change event? – Smeegs Nov 11 '13 at 19:32
  • If you want to select a specific list among others via javascript/jquery adding an ID is a good approach, although I'm also not sure what you're trying to achieve. – hugo der hungrige Nov 11 '13 at 19:34
  • overall goals not clear at all – charlietfl Nov 11 '13 at 19:51
  • Thanks for the feedback. My goal is to indeed to be able to select a specific list among others with JQuery so I can handle that list selected value. – Cyrille Nov 11 '13 at 20:32

1 Answers1

2

Supposing that there are a lot of selects with class mod_list you can use on() delegation:

$(document).ready(function () {
    $(document).on("change", ".mod_list", function () {
        // this is the select you changed the value
        var $changedValueSelect = $(this);
        // do stuff, ajax and so on
        // print in console the selected value
        console.log($changedValueSelect.val());
    });
});

Why delegation? Because you have dynamically appended elements in your page.

JSFIDDLE

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Also note that for jQuery versions less than 1.7 you will need to use the delegate() event handler. – heymega Nov 11 '13 at 19:41