zaraku27
zaraku27

Reputation: 15

Append a number to id in jQuery to be used in jQuery/JavaScript

I want to assign an id to variable and append clicked_id to that id. Then, I want to use it in openModal() function. My idea is like this:

JS file

var thismodal = "#myModal";

function openModal(clicked_id) {
    var trueModalId = thismodal + clicked_id;
    document.getElementById(trueModalId).style.display = "block";
}

HTML

    <img class="hover-shadow cursor card-img-top" src="images/dmc.png" id="1" onclick="openModal(this.id);currentSlide(1)" alt="">
    <div id="myModal1" class="modal"></div>

How do I make this work?

EDIT

There will be multiple instances of the HTML code. So to make them unique, I assigned numbers as id for img and add numbers to myModal. In the above instance, myModal1 is used since the id of img is 1. That's why I don't want to use myModal1 directly.

Upvotes: 1

Views: 1253

Answers (3)

Sowdhanya
Sowdhanya

Reputation: 63

Try this

function openModal(clicked_id) {
    if($(".modal").attr('id').indexOf(clicked_id)==-1)
    {
       $(".modal").prop("id", $(".modal").attr("id")+clicked_id);
    }
    var trueModalId = $(".modal").attr('id');
    alert($(".modal").attr('id'));
    document.getElementById(trueModalId).style.display = "block";
}

By using the class name you can append number to your id

Upvotes: 0

NullPointer
NullPointer

Reputation: 7368

Remove # and try this:

var thismodal = "myModal";

function openModal(clicked_id) {
    var trueModalId = thismodal + clicked_id;
    document.getElementById(trueModalId).style.display = "block";
}

Upvotes: 1

Juliver Galleto
Juliver Galleto

Reputation: 9037

Try this

var thismodal = "#myModal";

function openModal(clicked_id) {
    var trueModalId = thismodal + clicked_id;
    $(trueModalId).show();
}

Upvotes: 2

Related Questions