Marco Tck
Marco Tck

Reputation: 271

JQuery pass HTML ID as parameter

Here is my code:

HTML

<img src"../MyPic_1" id="MyImg_1" onclick = "MyJQfunction($(this))">
<img src"../MyPic_2" id="MyImg_2" onclick = "MyJQfunction($(this))">
<img src"../MyPic_3" id="MyImg_3" onclick = "MyJQfunction($(this))">

JQUERY

<script>
function MyJQfunction(MyField)
{
  MyField.hide();
}
</script>

As you can see I'm trying to send the HTML element to my JQ Function so it knows what to hide.

What am I doing wrong?

NOTE: This is just a simple example of what I really need to do, I just want to avoid including codes that you don't care about. Thanks!

Upvotes: 1

Views: 2243

Answers (3)

CodeGodie
CodeGodie

Reputation: 12132

This is what I would do:

<img src="../MyPic_1" id="MyImg_1" class="image_to_hide"/>
<img src="../MyPic_2" id="MyImg_2" class="image_to_hide"/>
<img src="../MyPic_3" id="MyImg_3" class="image_to_hide"/>

...

<script>
    $(".image_to_hide").click(function(){
        $(this).hide();
    });
</script>

Upvotes: 0

PSL
PSL

Reputation: 123739

You are using jquery so attach an event handler instead of using onclick

<img src="../MyPic_1" id="MyImg_1" class="myIMage">
<img src="../MyPic_2" id="MyImg_2" class="myIMage">
<img src="../MyPic_3" id="MyImg_3" class="myIMage">

and

$(function(){
      $('.myIMage').on('click', MyJQFunction);
 }

function MyJQFunction()
{
   $(this).hide(); //here this represents the element clicked.
}

Or classic way; use Function.call to set the context for the function while invocation.

<img src"../MyPic_1" id="MyImg_1" onclick = "MyJQfunction.call(this)">

and

function MyJQFunction()
{
   $(this).hide(); //and this here is now the clicked element.
}

Also in your code your image tag seems to be incorrect and MyJQfunction versus MyJQFunction has casing (note the casing of f) issue. Check your console for errors. Otherwise your code should work.

Upvotes: 1

Marcelo Biffara
Marcelo Biffara

Reputation: 831

You should wrap that on jquery function like this

function MyJQFunction(MyField)
{
  $(MyField).hide();
}

Upvotes: 0

Related Questions