简体   繁体   中英

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?

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.

$("select").change(function() {})

Looks like your JQuery is not loaded,check first that it is loaded

    //case if mini jQueryis not used replace with window.jQuery
    if (window.$) {
    console.debug('jQuery is loaded ');
    } else {
    console.debug('jQuery is not loaded ');
    }

Try bind:

  $("#selectattribute").bind('change', function() {
     alert('Handler for .change() called.');
  });

or change function in jQUery:

  $("#selectattribute").change(
     function() {
        alert('Handler for .change() called.');
     }
  ); 

也许还有另一个标签,其id被命名为“selectattribute”。标签id应该是唯一的。如果有多个id,jQuery将使用第一个id。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM