HPWD
HPWD

Reputation: 2240

How to pull the ID (or other attributes) from a JavaScript Object

I'm using the bootstrap plugin (http://www.bootstrap-switch.org/) and the event handler will give me tons of info - lot more than I need.

$('.make-switch').on('switch-change', function (e, data) {
    var $el = $(data.el)
    , value = data.value;
    console.log(e);
    console.log($el);
    console.log(value);
});

I just need the ID of the switch that has been switched as well as the state it is in. In Firefox firebug, I see in the console window, the following:

+ Object[input#checkbox_1]. When I drill down into the Object, I see a 0 so I click on that which expands further. Under the 0 I see the ID attribute and corresponding value I'm looking for but I don't know how to reference it. If I can get some help with this, getting the value will be the same method.

So my question is, how do I get the ID of the switch that has been thrown?

I tried using another SO question/answer and adapting it to this problem but it didn't work for me. I took this:

$("a").click(function(event) {
    console.log(event.target.id);
});

and adapted it to this:

$('.make-switch').on('switch-change', function (e, data, event) {
    var $el = $(data.el)
    , value = data.value;
    console.log(e);
    console.log($el);
    console.log(value);
            console.log(event.target.id); //but this produces an error
});

but the console.log(event.target.id) produces an error.

So my question is, how do I get the ID of the switch that has been thrown? (in case the question was missed above

Per a comment: here is a jsFiddle of what I started off with:
http://jsfiddle.net/zZWLx/1/

Upvotes: 0

Views: 164

Answers (2)

pax162
pax162

Reputation: 4735

Try this, inside the handler:

console.log($(e.target).attr("id"))

EDIT:

Try this, updated fiddle: http://jsfiddle.net/zZWLx/2/

code:

$(".make-switch").on('switch-change', function(event){
    console.log($(event.target).find("input").attr("id"));
})

Upvotes: 0

user2474948
user2474948

Reputation:

If You are using JQuery

$(document).ready(function() {
  $("a").click(function(event) {
    alert(event.target.id);
  });
});

Upvotes: 1

Related Questions