6

I have the following code that works each and every time an element change happens within my web form:

<!--

jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions

$(document).ready(function(){

    $(this).change(function(){
        alert('form element changed!');
    });

}); // end .ready()

//-->

What I have been struggling with is how to capture the form field element id, name and changed value when the change event is triggered.

Can anyone help me out on this?

Thanks!

** JAVASCRIPT FILE **

// Sarfraz
$(this).change(function(){
   var id, name, value;
   id = this.id, name = this.name, value = this.value;
    alert('id=' + id); // this returns 'undefined'
    alert('name=' + name); // this returns 'undefined'
    alert('value=' + value); // this returns 'undefined'
});
//

// rjz
$(this).change(function(){
  var $this = $(this),
    id = $this.attr('id'),
    name = $this.attr('name'),
    value = $this.val();

    alert(id); // this returns 'undefined'
    alert(name); // this returns 'undefined'
    alert(value); // this returns blank
});

// Jamie
$(this).change(function(){
    var id = $(this).attr('id');
    var name = $(this).attr('name');
    var value = $(this).attr('value');

    alert('id=' + id); // this returns 'undefined'
    alert('name=' + name); // this returns 'undefined'
    alert('value=' + value); // this returns 'undefined'
});
//

//James Allardice
$(this).change(function(e) {
    var elem = e.target;
    alert('elem=' + elem); // this returns 'objectHTMLTextAreaElement'
});
//

// Surreal Dreams
$("#my-form input").change(function(){
    alert('form element changed!');
    var value = $(this).val();
    var id = $(this).attr("id");
    var name = $(this).attr("name");

    alert(id); // nothing happens
    alert(name); // nothing happens
    alert(value); // nothing happens
});
//

//Jamie - Second Try
$('.jamie2').each(function() {
    $(this).change(function(){
        var id = $(this).attr('id');
        alert(id); // nothing happens
    });
});
//
H. Ferrence
  • 7,906
  • 31
  • 98
  • 161

8 Answers8

6

I think you may have a problem right from the start:

$("#myform input").change(function(){
    alert('form element changed!');
    var value = $(this).val();
    var id = $(this).attr("id");
    var name = $(this).attr("name");
});

You don't want to start with $(this), you need to select the inputs you want to monitor. Then you can use $(this) inside the change() function.

James Allardice pointed out that you may be referring to the form with $(this), and the change() event would catch all changes in the form. I'd suggest you target your changed elements more specifically so you're not catching change events on elements that you don't need or want, which could eliminate unexpected behavior. You could target them with a class or form selector like :input.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • I'll agree with this one until Dr. DOT provides additional information for why you would want to bind change to "this" rather than to particular inputs. ;-) I can't think of a good use case for `$(this).change()` yet, but that doesn't mean there isn't one. – Greg Pettit Mar 06 '12 at 19:43
  • @GregPettit - Since `this` refers to a `form` element, you can bind a `change` event handler to it and it will capture change events triggered by any descendant of it (as they will bubble up to the `form`). Like using `on` with a selector argument. See my answer. – James Allardice Mar 06 '12 at 19:44
  • If Dr. DOT provides some clarification, I'll be sure to make an update. Toss a comment down here Dr. DOT so I get a note to check it. – Surreal Dreams Mar 06 '12 at 19:45
  • @SurrealDreams - nothing happened when I tried your suggestion. See my code I appended to my answer – H. Ferrence Mar 06 '12 at 20:10
  • @JamesAllardice Gotcha; I was thinking of `this` as being the input, not the form. However, I still think selecting the form elements and binding change to them is easier than fiddling with 'this' as the starting point. – Greg Pettit Mar 06 '12 at 20:19
  • @GregPettit - It may be easier, but if there are lots of `input` elements it's far less efficient (you have one event handler instead of one for every single `input`). – James Allardice Mar 06 '12 at 20:20
  • @JamesAllardice True fact. You could always delegate the form as a listener for change events on inputs for the same net result but less confusing syntax (subjectively speaking, mind you). – Greg Pettit Mar 06 '12 at 20:27
  • @GregPettit - That's exactly what you would be doing if you bind the `change` event handler to the `form`. It's basically the same as doing `$("#myForm").on("change", "input", someFunction);`. – James Allardice Mar 06 '12 at 20:28
  • @SurrealDreams. Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:32
4

As far as I understand it, this refers to a form element and you want to get a reference to the descendant of that form element which triggered the event.

If that's right, you can use the target property of the event object:

$(this).change(function(e) {
    var elem = e.target;
});

Here's a working example.

In the above code, elem will refer to the element which triggered the event. You can then access properties of that element, such as id:

$(this).change(function(e) {
    var elemId = e.target.id;
});
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I got 'objectHTMLTextAreaElement' when I tried your sample. See code I appended to my question. – H. Ferrence Mar 06 '12 at 20:02
  • @Dr.DOT - Try `alert(e.target.id);`. `e.target` gets you the actual element. You can then access properties of it. I've updated my answer with another example. – James Allardice Mar 06 '12 at 20:03
  • YAHOO @JamesAllardice. You got me the closest thus far. I just saw the ID name. I am going to play around some with your sample. I'll report back. You're a star. So is everyone else who chimed in here. Thanks Everyone!!! – H. Ferrence Mar 06 '12 at 20:24
  • @Dr.DOT - Glad you made some progress :) – James Allardice Mar 06 '12 at 20:26
  • @JamesAllardice...I just alerted the changed value for the first time in like 3 days of wheel spinning. Thanks so much ! – H. Ferrence Mar 06 '12 at 20:27
  • If you have a moment, I have my next question as I build my app. Can you peek at http://stackoverflow.com/questions/9593517/prettyphoto-how-to-capture-form-elements-that-are-part-of-inline-text-lightbox and tell me if you have any ideas on my next issue? Thanks. – H. Ferrence Mar 06 '12 at 23:54
2

In order to use $(this), you must have a predefined JavaScript object. That's why it's called this.

So you need to do something like this:

$('.class_name').each(function() {
    $(this).change(function(){
        var id = $(this).attr('id');
    });
});

or

$('.class_name').click(function() {
    $(this).change(function(){
        var id = $(this).attr('id');
    });
});

In short, you need to select an element and create an object before you can use $(this).

hohner
  • 11,498
  • 8
  • 49
  • 84
  • @Jaimie. each of your sample code returns 'undefined'. See the code I appended to my question. – H. Ferrence Mar 06 '12 at 19:59
  • Thanks @Jaimie...but still no luck. See my code I appended to my question. – H. Ferrence Mar 06 '12 at 20:18
  • Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:30
1

You would do something like the following inside your change

var ELEMEMT = $('#IDOFELEMENT').val();
bretterer
  • 5,693
  • 5
  • 32
  • 53
  • Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:32
1

You can access the properties directly as follows:

$(this).change(function(){
  var id = this.id,
    name = this.name,
    value = this.value;
});

Alternatively, jQuery provides helper functions to retrieve these properties from the first element in a jQuery collection:

$(this).change(function(){
  var $this = $(this),
    id = $this.attr('id'),
    name = $this.attr('name'),
    value = $this.val();
});
rjz
  • 16,182
  • 3
  • 36
  • 35
  • Your first example is identical to Sarfraz. Your second example I tested as well. Both samples return undefined. See my JS code in my question. – H. Ferrence Mar 06 '12 at 19:56
  • Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:31
1

TRY with jQuery 1.7

$(document).on('change','#myID',function(){
    alert('Id:'+this.id+'\nName:'+this.name+'\nValue:'+this.value);
});​

DEMO

xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • I assumed #myID is in reference to my
    tag id. Correct? If so, nothing returned when I tired your suggestion.
    – H. Ferrence Mar 06 '12 at 20:05
  • Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:30
1

Here is how:

$(this).change(function(){
   var id, name, value;
   id = this.id; name = this.name; value = this.value;
});
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Thanks @Sarfraz. I tried your version a few days ago, but gave it another shot. See my code that appended to my question. All three elements return "undefined". – H. Ferrence Mar 06 '12 at 19:51
  • @Dr.DOT: You need to also clarify what does `this` refer to in your code, what html element and how does it reach till that code. – Sarfraz Mar 06 '12 at 19:54
  • @Dr.DOT: Yes but one can make it refer to objects in JS. That's what I am asking what object does it refer to? Or an element that you are grabbing with jQuery? You need to edit that information in your question. – Sarfraz Mar 06 '12 at 20:04
  • Thank you very much for helping me out. I was able to get what I set out too via James Allardice's `e.target.id` answer. I greatly appreciate your assistance. Best regards. – H. Ferrence Mar 06 '12 at 20:30
  • @Dr.DOT: You are welcome and glad to know that your problem was solved :) – Sarfraz Mar 07 '12 at 04:32
0

Well, I'm late to the party except in comment form, but just for posterity: here's my extension of Surreal Dreams' approach:

$("#myform").on('change', input, (function(){
    alert('form element changed!');
    var $this = $(this);
    var value = $this.val();
    var id = $this.attr("id");
    var name = $this.attr("name");
});

#myform listens for changes on inputs inside. I also cached the jQuery-wrapped this. Voila!

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72