Home Ask Login Register

Developers Planet

Your answer is one click away!

Amy Neville February 2016

Jquery Select Dynamic ID

I'm trying to toggle the visibility of this. You'll notice there's a primary key number at the end of the id:

<div id="campaign-details-container-12">

And this is how I've tried to select it:

$(document).on("click",".show-details",function () {
    $(this).blur();
    var id = $(this).data("id");
    var selector = "#campaign-details-container-"+id;
    alert(selector);

    $(selector).toggle();
    return false;
});

How can I get this to work? I could put a data-id="12" tag in the div instead and use a class, but how would I select by that?

Answers


seahorsepip February 2016

Just select it using the attribute starts with syntax:

$("[id^=campaign-details-container]");

No need to go do unnecessary things with classes and id variables...

See http://www.w3schools.com/cssref/sel_attr_begin.asp


Punit Gajjar February 2016

I think you are trying something like this .

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a data-id="12" class="show-details"> Show Details </a>
<div id="campaign-details-container-12"> Test Content Here </div>


<script type="text/javascript">

    $(document).on("click",".show-details",function () {
        $(this).blur();
        var id = $(this).data("id");
        var selector = "#campaign-details-container-"+id;
        $(selector).toggle();
        return false;
    });
</script>

Post Status

Asked in February 2016
Viewed 1,857 times
Voted 12
Answered 2 times

Search




Leave an answer


Quote of the day: live life