Ray
Ray

Reputation: 780

The Change Event Jquery?

could somebody tell me what's wrong with the following code:

<html>
    <head>
    </head>
    <body>
        <select name="target">
            <option value="item1">item1</option>
            <option value="item2">item2</option>
            <option value="item3">item3</option>
        </select>
    </body>
</html>
<script>
    $(".target").change(function () {
        alert("Handler for .change() called.");
    });
</script>

Nothing alert on item change!!? Am I missing something Thanks.

Upvotes: 0

Views: 261

Answers (2)

Alnitak
Alnitak

Reputation: 339816

Put an id on your select element and use that in the selector instead:

Names are for form submission, IDs should be used for DOM traversal:

$('#target').on('change', function() {
  alert('changed to ' + this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="target" id="target">
  <option value="item1">item1</option>
  <option value="item2">item2</option>
  <option value="item3">item3</option>
</select>

NB: .on('change', ...) rather than .change(...) will make it easier to find your event registrations in your code.

Upvotes: 2

George
George

Reputation: 36784

Currently you are attaching the event handler to all elements with the class target, whereas the element you want to target has the name target.

You need to use an attribute selector:

$("select[name=target]").change(function () {
    alert("Handler for .change() called.");
});

Or, apply a matching class to your element:

<select name="target" class="target">
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

Upvotes: 2

Related Questions