2

I have a css class (.SideOption) which has multiple instances on a page and I want to have something to differentiate between them (so I chose ID), but I can't get JS to get the ID, it just returns undefined in the alert box.

JS;

function CreateBox()
{
    $MyID = this.id;
    alert($MyID);
}

$(document).ready(function() 
{
    $(".SideOption").click(function() 
    {   
        CreateBox();
    })
})

This is what the SideOption looks like for example.

<div class="SideOption" id="1">
</div>
Aaron
  • 171
  • 1
  • 9

2 Answers2

3

You could use the call() method to invoke the function with the context of this (example)

function CreateBox() {
    $MyID = this.id;
    alert($MyID);
}
$(".SideOption").click(function () {
    CreateBox.call(this);
});

Alternatively, you could pass a reference to the CreateBox function when the element is clicked (example)

function CreateBox() {
    $MyID = this.id;
    alert($MyID);
}

$(".SideOption").click(CreateBox);

(For what it's worth, a CSS selector cannot begin with a number.)

Community
  • 1
  • 1
Josh Crozier
  • 202,159
  • 50
  • 343
  • 273
1

You have to fix your JS like this: http://jsfiddle.net/csdtesting/ajnm3o4m/

Pass the element to CreateBox function and then take the attribute "id" with element.id or with $(element).attr("id").

function CreateBox(element) {
    $MyID = element.id;
    alert($MyID);
}

$(".SideOption").click(function () {
    CreateBox(this);
})

Hope it helps!

Giannis Grivas
  • 3,187
  • 1
  • 13
  • 36