Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  31] [ 4]  / answers: 1 / hits: 39257  / 12 Years ago, mon, december 10, 2012, 12:00:00

I have a modal box in jQuery which I have created to display some embed code. I want the script to take the id of the link that is clicked but I can't seem to get this working.



Does anyone know how I can do that or why this may be happening?



My jQuery code is:



function generateCode() {
var answerid = $('.openembed').attr('id');
if($('#embed input[name=comments]:checked').length > 0 == true) {
var comments = &comments=1;
} else {
var comments = ;
}
$(#embedcode).html('<code>&lt;iframe src=embed.php?answerid=' + answerid + comments + ' width=550 height=' + $('#embed input[name=size]').val() + ' frameborder=0&gt;&lt;/iframe&gt;</code>');
}

$(document).ready(function () {
$('.openembed').click(function () {
generateCode();
var answerid = $('.openembed').attr('id');
$('#box').show();
return false;
});
$('#embed').click(function (e) {
e.stopPropagation()
});
$(document).click(function () {
$('#box').hide()
});
});


My mark-up is:



<a href=# id=7830 class=openembed>Embed</a>
<a href=# id=9999 class=openembed>Embed</a>

More From » jquery

 Answers
10

Your problem is here:



$('.openembed')


returns an array of matched elements. Your should instead select only the clicked element.
$('.openembed') works correctly if you assing a click event to all elements that have this class. But on the other hand, you're unable do know which is clicked.



But fortunately in the body of handler function click you could call $(this).



$(this) will return the current (and clicked element).



// var answerid = $('.openembed').attr('id'); // Wrong
var answerid = $(this).attr('id'); // Correct
// Now you can call generateCode
generateCode(answerid);


Another error is the body of generateCode function. Here you should pass the id of selected element. This is the correct implementation.



function generateCode(answerid) {
if($('#embed input[name=comments]:checked').length > 0 == true) {
var comments = &comments=1;
} else {
var comments = ;
}
$(#embedcode).html('<iframe src=embed.php?answerid=' + answerid + comments + ' width=550 height=' + $('#embed input[name=size]').val() + 'frameborder=0></iframe>');
}


Here I have implemented your code with the correct behavior: http://jsfiddle.net/pSZZF/2/


[#81498] Sunday, December 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josuea

Total Points: 609
Total Questions: 121
Total Answers: 104

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
josuea questions
;