Michela Zanni
Michela Zanni

Reputation: 15

getting HTML attribute value

I have an image with a magnifier. When I click on the magnifier I want to open a modal window with a larger image. Here is my HTML:

<div class="col-sm-2 col-sm-offset-1">
    <div class="carousel-caption"><p>Fontana dei Cappuccini</p></div>
    <a href="#x" class="thumbnail"><img id="cappuccini" class="photoThumbnail" src="../img/fontane/FontanaDeiCappuccini.jpg" alt="Fontana dei Cappuccini" style="cursor:pointer" title="FontanaDeiCappuccini"></a>
    <img class="magnifier" id="cappuccini-mgf" src="../icons/lenteIngrandimento.png" alt="mgf" style="cursor:pointer">
</div>

<div id="imgModal" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Titolo del modal uguale ad alt dell'immagine</h4>
            </div>
            <div class="modal-body" id="imgLarge">
            </div>
            <div class="modal-footer">
            <p>Photo by me</p>
            </div>
        </div>
   </div>
</div>

and my Jquery:

$(".magnifier").click(function(){
    var mgf_id_value = this.id.slice(0,-4); 
    console.log(mgf_id_value);  
    var mod_img = $(".photoThumbnail[id=mgf_id_value]");
    console.log(mod_img);
    var mod_img_alt = $(mod_img).attr("alt");
    console.log(mod_img_alt);
$('#imgModal').modal('show');
});

var mod_img = $(".photoThumbnail[id=mgf_id_value]"); doesn't work. If I use a given id value ('cappuccini' for instance) it works, but if I try using var mgf_id_value the result is undefined. I don't understand where I'm wrong.

Thank you in advance. M.Z.

Upvotes: 0

Views: 47

Answers (3)

StefanSL
StefanSL

Reputation: 317

You could use this selector:

var mod_img = $("#" + mgf_id_value + ".photoThumbnail" );

But it's better not to search the whole DOM again:

var mod_img = $(this).parent().find('.photoThumbnail')

Upvotes: 0

Damian
Damian

Reputation: 173

the selectors in jquery are identical to the ones of css.

so if you want to capture an image (tag 'img') with and id 'mgf_id_value' and class of 'photoThumbnail'

you will write

var mod img = $("img#" + mgf_id_value + ".photoThumbnail")

Upvotes: 0

lplatz
lplatz

Reputation: 101

When you do var mod_img = $(".photoThumbnail[id=mgf_id_value]"); the mgf_id_value variable is interpreted as the variable string itself (aka it's literally using the string value "mgf_id_value") because its inside quotes. Try

var mod_img = $(".photoThumbnail[id="+mgf_id_value+"]");

Upvotes: 1

Related Questions