How can I detect in jQuery when any option in a select tag has been changed?
For example [pseudocode]:
event handler function -> option changed(){
//do some stuff
}
EDIT:
I have the following select:
<select id = "selectattribute">
<OPTION VALUE="0">Choose Attribute</OPTION>
<?php echo($options);?>
</select>
I am trying this in jQuery:
$(document).ready(function() {
$("#selectattribute").change(function() {
alert('Handler for .change() called.');
});
});
Nothing happens...the function isn;t triggering.
EDIT: it works when I use $("#select")
instead of $("#selectattribute")...can you not apply it to particular select tags?
A more direct jQuery method to the option selected would be: var selected_option = $('#mySelectBox option:selected'); Answering the question .is(':selected') is what you are looking for: $('#mySelectBox option').
The selectedIndex property sets or returns the index of the selected option in a drop-down list. The index starts at 0. Note: If the drop-down list allows multiple selections it will only return the index of the first option selected. Note: The value "-1" will deselect all options (if any).
Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} .
From jQuery docs regarding the change handler:
<form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
The event handler can be bound to the text input and the select box:
$('.target').change(function() {
alert('Handler for .change() called.');
});
Your Code works in Firefox using the mouse, see this fiddle.
However using the keyboard is a different matter as per this bug report
To work around this I've added a key up handler to remove focus from the element then re-focus, as per this fiddle
If the change event is not triggering when using the mouse, check the options rendered by your php code. Look for structures that might be "breaking" the select tag.
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