Daft
Daft

Reputation: 10964

How do I pass a div Id as a parameter in jQuery??

I have three divs and Id like to add a click function to them. Ideally, I'd like them all to use the same function and use ther ID as a param

When I run this, I get an alert with 'leftBox', no matter which box I click.

Can someone explain what Im doing wrong??

$('<div id="imageBoxOne">< src="images/carOne.jpg"></div>');
$('<div id="imageBoxTwo">< src="images/carTwo.jpg"></div>');
$('<div id="imageBoxThree">< src="images/carThree.jpg"></div>');

$("#imageBoxOne").click(moveImages);
$("#imageBoxTwo").click(moveImages);
$("#imageBoxThree").click(moveImages);

function moveImages(imageId) {
    if (imageId = imageBoxOne){
        alert('leftBox');
    }

    else if (imageId = imageBoxTwo){
        alert('middleBox');
    }
    else {
            alert('rightBox');
    }
};

Upvotes: 0

Views: 5056

Answers (5)

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You can get it using this.id inside the function.

When you do the following. You assign the value of imageBoxOne to imageId you should use ==.

imageId = imageBoxOne

Upvotes: 0

Ayush
Ayush

Reputation: 42440

The argument passed by the click event is the event, which contains a lot of information. You can get the ID like this:

function moveImages(e) {
  var id = e.target.id;
}

To get the parent div's id:

function moveImages(e) {
   var id = $(e.target).parent().attr('id');
}

Upvotes: 1

SLaks
SLaks

Reputation: 887285

imageId = imageBoxOne

This assigns imageId to the non-existent imageBoxOne variable.

You want to compare them using ===, and you want a string literal using "...".

Also, imageId is actually the event object. You can get the element that you added the handler to from this, and gets its id property (this.id)

Upvotes: 2

Ram
Ram

Reputation: 144669

In your function imageId refers to the event object, not the ID of the element, you should use this keyword. Also note that you are setting the value instead of comparing it.

function moveImages(imageId) {
    if (this.id === 'imageBoxOne') { 
        alert('leftBox');
    }
    // ...

Upvotes: 4

Marcus
Marcus

Reputation: 6117

You're using "=" rather than "==" or usually better "===".

Upvotes: 0

Related Questions