Hi DW, I'm trying to get selected option id, the problem with my code is that it is only showing or returning the id of the first select only even if I click other options it doesn't return them.
Heres my code

var xid = $('#managsel option:selected').attr('id');
alert("The id is: " + xid);

Here is my select option code NB: The code is generated by php.

<select class="form-control select2" style="width: 100%;" id="managsel">
<option selected="selected">Select Department</option>
<option id="opa">Accountant</option>
<option id="opb">Training</option>
<option id="opc">Operations</option>
<option id="opd">IT</option>
</select>

Also note that the options id are generated dynamically and I don't know them beforehand.
Thank you.

The code listens for a change event on a <select> element and displays the value (ID) of the selected option in a paragraph. It updates dynamically when the user selects a different option.

commented: On my end it only work when you click Accountant and does return it id which is opa but when I click the others it doesn't work at all. +8

What I mean is that I have a table that is dynamically generated with and each record generate the same select as you can see above.

Now the problem is that the code only work with the first table record select, from the table.

I have many select with the same id and I need to get their options id when that particular select is changed.

The code that I have only work or gets one select and does not work on the rest of the selects except the first one.

I've also tried using a query select all but that doesn't even work with the first one as well.

I've managed to use an alternative, instead of this approach I've changed and used a function call onChange="Myfunction(this);" and I then reference to the dom element returned to get it option selected id.

It is now working accordingly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.