ak-SE ak-SE - 1 month ago 10
PHP Question

How to assign dynamic element id in jQuery when onMouseOver in a href tag?

I have 3 hyperlinks and DIV randomly generated by PHP script with dynamic ids. For example,

<a href="http://www.example.com/find.php?id=xy1" id="xy1" onMouseover="analyze('final', 'xy1')">xy1</a>
<a href="http://www.example.com/find.php?id=ay2" id="ay2" onMouseover="analyze('final', 'ay2')">ay2</a>
<a href="http://www.example.com/find.php?id=am3" id="am3" onMouseover="analyze('final', 'am3')">am3</a>

<div id="xy1"></div>
<div id="ay2"></div>
<div id="am3"></div>


I want to display some text based on the
onMouseover
event through a function
analyze()
in jQuery. For example,

function analyze(db, target) {
jQuery.ajax({
type: "GET",
url: "toThumb.php",
data: 'db=' + db + '&id=' + target,
success: function(output){ $("#"+target).html(output); }
});
}


Here, the element id
#xy1
must be automatically assigned based on
onMouseover
event. Like xy1 as a value of a variable name. Maybe on the next
onMouseover
event it will be ay2 or am3.

I tried to set with
$("#"+target).html(output);
It failed... If I test individually with
$("#xy1").html(output);
OR
$("#ay2").html(output);
OR
$("#am3").html(output);
It works fine.

Does my way of coding is wrong? Or, Can I use
this
instead of passing parameters?

Answer

First of all id should be unique in DOM. And in place of it you can use class as below.

Please check below working demo.

function analyze(ele){
  $("."+ele.id).html(ele.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.example.com/find.php?id=xy1" id="xy1" onMouseover="analyze(this)">xy1</a>
<a href="http://www.example.com/find.php?id=ay2" id="ay2" onMouseover="analyze(this)">ay2</a>
<a href="http://www.example.com/find.php?id=am3" id="am3" onMouseover="analyze(this)">am3</a>

<div class="xy1"></div>
<div class="ay2"></div>
<div class="am3"></div>

Comments