Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
190
rated 0 times [  196] [ 6]  / answers: 1 / hits: 5587  / 11 Years ago, sun, january 19, 2014, 12:00:00

When a button is clicked a listener fires and a modal opens, and I need to get the info from the button clicked to be passed into the listeners that fire when stuff happens inside the modal.



My JavaScript:



$('li.tab').on('click', 'span.edit-tab', function() {
var elem = $(this);
var tabName = elem.parent().text();
tabName = tabName.replace(/s*$/g, '');
$('#tab-name').val(tabName);
$('#tab-name').on('keypress', function(elem) {
var appendedSpan = '';
appendedSpan += ' <span class=edit-tab glyphicon glyphicon-pencil ';
appendedSpan += 'data-toggle=modal data-target=#edit-tab-modal></span>';
var newName = $(this).val() + appendedSpan;
el.parent().html(newName);
});
});


I'm trying to pass in the element that triggered the modal to be passed into the listener of an input, but no matter what I try to pass in, the variable elem is the jQuery object for #tab-name, not for span.edit-tab. Any thoughts?


More From » jquery

 Answers
2

I think the only thing you need is to save eventData and $popupTriggerElem outside the keypress context:



$('.popupTrigger').on('click', function(popupEventData) {
var $popupTriggerElem = $(this);
$('#tab-name').on('keypress', function(tabEventData) {
var $tabElem = $(this);
//now you can use all 4 variables:
console.log(popupEventData);
console.log($popupTriggerElem);
console.log(tabEventData);
console.log($tabElem);
});
});


This way you have access to:
- element which triggered click event,
- click event data
- element which triggered keypress event
- keypress event data



It's JS's awesomness that each parent context for any function/object you're currently in is kept till the function/object will be removed from memory.



EDIT:



As you can see in @Wynand comment this behavior is based on closures. More in MDN docs.


[#48552] Saturday, January 18, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everett

Total Points: 317
Total Questions: 112
Total Answers: 109

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;