Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - event handler to detect if HTML select option has been selected

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?

like image 290
user906568 Avatar asked Aug 23 '11 00:08

user906568


People also ask

How do you check if any option is selected in jQuery?

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').

How do I know which option is selected in HTML?

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).

How do you check whether a dropdown is selected or not?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} .


2 Answers

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.');
});
like image 153
Jon Adams Avatar answered Sep 28 '22 07:09

Jon Adams


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.

like image 26
Jon P Avatar answered Sep 28 '22 07:09

Jon P