JIMMY JIMMY - 5 months ago 27
jQuery Question

Jquery passing the retrieved value to another id

This is my first day using Jquery, I want to retrieve the id from the clicked element and pass the id to another element. So far I know that the id fetch is working fine according to my code, but I'm unable pass the value to another element! Idk where I'm going wrong.
Here is the code.

$(function() {
$(".prs").click(function(e) {
e.preventDefault();
var x= $(this).get(0).id);
$("span #x").slideToggle("slow");
});
});


I want to pass the retrieved id to the id of span as in last line of code.

Answer

This has nothing to do with jQuery, it's a JavaScript matter. You need to concatenate the string and your variable. Try this:

$(function() {
    $(".prs").click(function(e) {
        e.preventDefault();
        var x= $(this).get(0).id);
        $("span #" + x).slideToggle("slow");
    });
});

However, just a side note. You don't need jQuery to get the id. Simply use JavaScript like this:

var x= this.id;

So your code can be simplified like this:

$(function() {
    $(".prs").click(function(e) {
        e.preventDefault();
        $("span #" + this.id).slideToggle("slow");
    });
});

Finally, just a comment about the ids, it's not valid HTML to have two items with the same id. So you'll have to give them different ids, let say my_object for the clickable element and my_oject_box for the span. Then your code becomes:

$(function() {
    $(".prs").click(function(e) {
        e.preventDefault();
        $("#" + this.id + "_box").slideToggle("slow");
    });
});