Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data attributes in jQuery/Coffee script

I have the following form code:

 <input data-color="orange" id="vote_color_id_2" name="color" type="radio" value="2" />Orange
 <input data-color="blue" id="vote_color_id_3" name="color" type="radio" value="3" />Blue
 <input data-color="green" id="vote_color_id_4" name="color" type="radio" value="4" />Green

I'm using Coffee script in rails and right now I'm just trying to alert the value of the data attribute data-color.

This is my coffee script

jQuery ->
    $("input[name='color']").change ->
        color = this.data()
        alert color.color

The compiled jQuery looks like this:

(function() {

  jQuery(function() {
    return $("input[name='color']").change(function() {
      var color;
      color = this.data();
      return alert(color.color);
    });
  });

}).call(this);

But I keep getting this error?

Uncaught TypeError: Object #<HTMLInputElement> has no method 'data'
like image 201
Slick23 Avatar asked Feb 29 '12 00:02

Slick23


1 Answers

jQuery ->
    $("input[name='color']").change ->
        color = $(this).data()
        alert color.color

jQuery assigns this to the element that triggered the callback, but its never a jQuery object. So you have to wrap it if you want to call jQuery methods on it.

like image 141
Alex Wayne Avatar answered Nov 09 '22 02:11

Alex Wayne