5

Lets say i have one dropdown on the page, when the user clicks a button to create more dropdowns with the same options, i want to be able to enable and disable the selected options from all of the dropdowns on the page.

<select>
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="2">Jane Smith</option>
<option value="3">John Doe</option>
</select>    

I know that this Jquery works for static dropdowns

$("select").change(function () {
    $("select option[value='" + $(this).data('index') + "']").prop('disabled', false);
    $(this).data('index', this.value);
    $("select option[value='" + this.value + "']:not([value='0'])").prop('disabled', true);
});

But it doesn't seem to work for dynamically created dropdowns. Only the selected option from the first dropdown gets disabled in the others, it doesnt work the other way round

Here is my simplified create code:

function createRow() {
var table = $('#addTable');

table.append('<select class="ui fluid search dropdown" ><?php foreach ($taskdescriptions as $task) : ?> <option value="<?php echo $task ?>"><?php echo str_replace("|"," ",$task);  ?></option><?php endforeach; ?></select>');
    $("select option[value='" + $(this).data('index') + "']").prop('disabled', false);
    $(this).data('index', this.value);
    $("select option[value='" + this.value + "']:not([value='0'])").prop('disabled', true);


}

I am creating table rows, where each row has a select dropdown and some other inputs

  • can you post the code you're using to create the dynamic elements? – Nikki9696 Dec 20 '19 at 16:05
  • 3
    if the change event is not firing for dynamically created dropdowns, see https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Heretic Monkey Dec 20 '19 at 16:08
  • 2
    ok, I think the link above is what I was thinking of - use the "on" type of binding and see if that works out for you (instead of just "change") - specifically the Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time – Nikki9696 Dec 20 '19 at 16:19

1 Answers1

3

Thanks to Heretic Monkey and Nikki9696 The solution is:

$('#addTable').on('change', 'select', function(){
    // code here
})
Samuel Asor
  • 480
  • 8
  • 25