1

I have a number of elements on a HTML forms, similar to the following:

<div class="area">
    First Area
    <select class="area_select" name="area_25" id="form_area_25">
        <option value="0" selected="selected">No</option>
        <option value="1" >Don't Mind</option>
        <option value="2" >Yes</option>
    </select>
</div>

<div class="area">
    Second Area
    <select class="area_select" name="area_13" id="form_area_13">
        <option value="0" selected="selected">No</option>
        <option value="1" >Don't Mind</option>
        <option value="2" >Yes</option>
    </select>
</div>
    .... and many more

They all have a class of area_select, and id of form_area_id where id as a unique integer.

I am trying to use jQuery to write an event handler for when the user changes a select box.

All I've managed to get so far is this:

$(".area_select").change(function() {
  alert('select changed, but no idea which one');
});

Is there any way to let the event handler know exactly which select is the source of the event?

NickJ
  • 9,380
  • 9
  • 51
  • 74

5 Answers5

2

this within the even refers to the control that fired the event:

$('.area_select').change(function(){
  // this = the control
});

Is that what you're going for? Or you can accept e in the callback and look at e.target.

$('.area_select').change(function(e){
  // e.target = the control (unless bubbling occurred)
});

Docs on event.target

If you wanted to get the ID of the select (just the number) you could use:

$(".area_select").change(function() {
    var selectid = this.id.match(/(\d+)$/)[1];
});
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

You can use this for source object and this.id for source object id.

Live Demo

$(".area_select").change(function(event) {
  alert(this.id);
});
Adil
  • 146,340
  • 25
  • 209
  • 204
1

you can use $(this) to get the control that triggered the event

$(".area_select").change(function() {
   alert($(this).attr("id") + " changed");
});
Simon McLoughlin
  • 8,293
  • 5
  • 32
  • 56
1

this is the source. Indeed, the function you bind to an event is invoked in the context of the item in which the event occurs. So it's simply:

$(".area_select").change(function() {
  alert('select ' + $(this).attr("id") + " changed");
});
Walid
  • 1,262
  • 11
  • 10
  • 1
    You should use [`.prop()` over `.attr()`](http://stackoverflow.com/questions/5874652/prop-vs-attr), especially if you're going to access native [properties](https://developer.mozilla.org/en-US/docs/DOM/element#Properties). Even better is excluding jQuery altogether and just referencing [`this.id`](https://developer.mozilla.org/en-US/docs/DOM/element.id). – Brad Christie Apr 11 '13 at 15:39
1

I think you need this :

$(".area_select").change(function() {
      alert('select changed: '+$(this).val()+' , but no idea which one: '
      +$(this).attr('id').replace('form_area_',''));
});
Mohamed AbdElRazek
  • 1,654
  • 14
  • 17