I am using jQuery to add an event to a select (multiple) control. The idea is to execute this event when an item is added or removed from the list. I have tried the $("#myselect").change()
function but this only throws the event when you select another item in the list. Any help would be greatly appreciated. Thanks in advance!
UPDATE:
HTML (auto generated for this example I put my id)
<select id="myselect" style="width: 143px; height: 125px; overflow: scroll;" ondblclick="GipRemoveSelectedItems(ctl00_ctl19_g_f081466b_5035_4884_b6db_009508a22e1c_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m); return false" onchange="GipSelectResultItems(ctl00_ctl19_g_f081466b_5035_4884_b6db_009508a22e1c_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m);" multiple="multiple" jQuery172007786130460086404="3"/>
jQuery - Inside of $(document).ready()
$("#myselect").change(function() {
//Does not enter on add or remove of an item
});
When an event handler is added using . on( "click", function() {...} ) , it can be triggered using jQuery's . trigger( "click" ) because jQuery stores a reference to that handler when it is originally added. Additionally, it will trigger the JavaScript inside the onclick attribute.
Method 1: Append the option tag to the select box The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.
The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes. $( "#target" ).
You can use DOMSubtreeModified
event and check if new element added to DOM. i.e, In your case new option
to specific select
.
$("#SELECT_ID").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
DEMO FIDDLE
You can listen to the DOMNodeInserted
event and check if the new element is an option
into the specific select
.
Check: How to call a function in every element in the DOM even if they are dynamically created
Note the current answers have been deprecated in favour of the MutationObserver
API.
The correct way is now like so:
$select = $('#myselect')
const observer = new MutationObserver(
() => { $select.trigger('mutated') }
)
observer.observe($select[0], { childList: true })
Then to do something on the event trigger:
$select.on('mutated', () => { console.log('mutated') })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With