Declare a variable for use later in the code? - javascript

I am trying to understand how I can declare a variable that I can use later on in my jquery code. Below I am trying to use var id but it seems to be forgotten by the time I try to use it in an alert(id). How can I do this? Many thanks.
$(document).ready(function() {
$('.credit_btn').on('click', function() {
//Declare variables
var id = ($(this).prop("value"));
var test_id = $(this).parent().parent().attr("id");
//Load modal
$('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
function() {
$('#myModal').modal({
show: true
});
}
);
});
$(document).on("click", ".myBtn", function() {
alert(id); //Var id is lost.
});
}); //close doc

Declare var id publically instead of inside that $('.credit_btn').on('click', function() { and you are done.
Your current code:
$(document).ready(function() {
$('.credit_btn').on('click', function() {
//Declare variables
var id = ($(this).prop("value"));
var test_id = $(this).parent().parent().attr("id");
//Load modal
$('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
function() {
$('#myModal').modal({
show: true
});
}
);
});
$(document).on("click", ".myBtn", function() {
alert(id); //Var id is lost.
});
});
Change to:
$(document).ready(function() {
var id;
$('.credit_btn').on('click', function() {
//Declare variables
id = ($(this).prop("value"));
var test_id = $(this).parent().parent().attr("id");
//Load modal
$('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id,
function() {
$('#myModal').modal({
show: true
});
}
);
});
$(document).on("click", ".myBtn", function() {
alert(id); //Var id is lost.
});
});

As with all lexical scoping, declare id in a block such that everywhere it's used is in the same block or a descendant block:
$(document).ready(function() {
var id;
$('.credit_btn').on('click', function() {
id = ($(this).prop("value"));
var test_id = $(this).parent().parent().attr("id");
//Load modal
$('.modal-container').load('modalbox.php?id=' + id, '&position_id=' + test_id, function() {
$('#myModal').modal({
show: true
});
});
});
$(document).on("click", ".myBtn", function() {
alert(id);
});
}); //close doc

Try to declare the variable outside of callback function scope then use it inside the callback function
$( function() {
var id;
$('.credit_btn').on('click', function() {
id=1;
})
} );

Related

on event don't trigger after replaceWith()

When i click on a <span>, the span changes to an input field
$('table td').on('click', 'span', function() {
var $el = $(this);
var $input = $('<input/>').val($el.text()).attr('class', 'form-control');
$el.replaceWith($input);
var save = function() {
var $p = $ ('<span>').text( $input.val() );
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$('input').on('change', function() {
var target = $(this);
$.ajax({
url: 'url',
data: {
value: target.val(),
ruleId: target.data('rule'),
date: target.data('date')
},
type: 'POST',
success: function(data) {
console.log('updated');
}
});
});
After it, i need to catch when the input changes
But it does not trigger the $('input').on('change', function() { function anymore...
Can you try to use this instead
$(document).on('change','input',function(){
// your code here
}
Hope the helps
bind event to document and not to element will solve your problem.
$(document).on('change', '.item', function(event) {
refer jQuery doc

How to combine two jQuery functions

Good Morning.
I want to combine my jQuery functions into one.
$('body').on('click', '.toggle2', function() {
console.log(123);
$('body').find('.dateshow').toggleClass('show');
});
$('body').on('click', '.toogle3', function() {
$('body').find('.autorshow').toggleClass('show');
});
$('body').on('click', '.toogle4', function() {
console.log(123);
$('body').find('.starshow').toggleClass('show');
});
Many thanks in advance
If you change all of your toggle links to have the following markup:
click
click
click
Then you can add a more generic handler such as:
$('.toggle').on('click', function() {
var targetSelector = $(this).attr('data-toggle');
$('.' + targetSelector).toggleClass('show');
});
Codepen: http://codepen.io/anon/pen/aBKJEb
When a callback is called jQuery will pass in an event object. You can check the target of the event and process as needed.
$('body').on('click', '.toggle2, .toogle3, .toogle4', function(e) {
var $target = jQuery(e.target),
$targetObject;
if($target.hasClass('toggle2')) {
$targetObject = jQuery('body').find('.dateshow');
}
if($target.hasClass('toogle3') {
$targetObject = jQuery('body').find('.autorshow');
}
if($target.hasClass('toogle4') {
$targetObject = jQuery('body').find('.starshow');
}
$targetObject.toggleClass('show');
});
$('body').on('click', '.toggle2,.toogle3,.toogle4', function() {
var mapper = {
'toggle2': { cls: '.dateshow', console:true },
'toggle3': { cls: '.autorshow', console:false },
'toggle4': { cls: '.starshow', console:true }
};
this.classList.forEach(function(cls) {
var obj = mapper[cls];
if(obj) {
obj.console && console.log(123);
$('body').find(obj.cls).toggleClass('show');
}
});
});

jQuery get id of element that triggered event from nested function

How do I get the id of the ".item" element from inside the getJSON function?
jQuery(document).ready(function() {
$(".item").tooltip({
items: "div",
content: function(callback) {
$.getJSON('mydata.json', function(data) {
var country = event.target.id;
console.log(country);
});
}
});
});
I've seen an explanation here, but I'm not sure how to pass the event(s) in my case.
In your content callback, this refers to the element whose tooltip is being invoked, so you could use this.id to get the id of the current element
jQuery(function ($) {
$(".item").tooltip({
items: "div",
content: function (callback) {
var el = this;
$.getJSON('mydata.json', function (data) {
var country = el.id;
console.log(country);
});
}
});
});
This is how I would do it
jQuery(document).ready(function() {
$(".item").tooltip({
items: "div",
content: function(callback, this) {
var $obj = $(this);
$.getJSON('mydata.json', function(data, $obj) {
var country = event.target.id;
console.log(country);
console.log($obj.attr("id"));
});
}
});
});
Try to use the
$(this)
to access the current element, then you can access its ID by using
$(this).attr('id')
See http://jqueryui.com/tooltip/#custom-content

Twitter bootstrap:Popop are not showing up on first click but show up on second click

Here is my code. Please help me
$(document).ready(function(){
$(document).delegate(".view","click",function(){
var id = $(this).attr("id");
alert(id);
$("#"+id).popover({
html : true,
content: function() {
return $("#"+id+"tt").html();
},
title: function() {
return $('#popoverTitle').html();
}
});
alert("thisa");
});
});
Try replacing the function .delegate() by .on(), this function has been superseded in the last versions of Jquery.
jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
jQuery 1.7+
$( elements ).on( events, selector, data, handler );
The code would be:
$(document).ready(function(){
$(document).on("click",".view",function(){
var id = $(this).attr("id");
alert(id);
$("#"+id).popover({
html : true,
content: function() {
return $("#"+id+"tt").html();
},
title: function() {
return $('#popoverTitle').html();
}
});
alert("thisa");
});
});
Try doing this way..
$('.view')
.popover({trigger: 'manual'})
.click(function() {
if($(this).hasClass('pop')) {
$(this)
.popover('hide')
.removeClass('pop');
} else {
var id = $(this).attr("id");
var title = $('#popoverTitle').html();
var response = $("#"+id+"tt").html();
$(this)
.attr({'title': title, 'data-content': response})
.popover('show')
.addClass('pop');
}
});

How to call function in jquery plugin?

(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
};
//.....
};
})(jQuery);
call it in doucument ready in another file
$('#top_slides').top_islides();
$('#top_slides').top_islides().ajax_init();
I thought it should work ,I got an error, what's the problem?
Do it like this:
(function($) {
//Assuming $.fn.top_islides is defined
$.fn.top_islides.ajax_init = function(){
init_islides();
setTimeout(picmove,300);
};
//.....
})(jQuery);
Or
(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(picmove,300);
};
return {
ajax_init: ajax_init
};
});
//.....
})(jQuery);
Try something like this as in the example below:-
<script type="text/javascript">
$.someplugin = {
CallMe : function() {
alert("You called?");
},
otherstuff : function() { alert("other stuff!"); }
};
$.someplugin.CallMe();
$.someplugin.otherstuff();
</script>
when using var inside a function, it will make the element "private". it's a hacky way to make visibility in Javascript work, while true class structure don't come to Javascript.
You need to either set it to the prototype of your function or to return an object
(function($) {
$.fn.top_islides = function(){
var ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
};
return {
'ajax_init': ajax_init
};
//.....
};
})(jQuery);
or
(function($) {
$.fn.top_islides = function(){
//.....
};
$.fn.top_islides.prototype.ajax_init = function(){
init_islides();
setTimeout(function(){picmove()},300);
}
})(jQuery);
but in your case, you won't be using prototype, since you aren't instantiating a new top_islides object, but accessing through jQuery, so the first option is your best bet.
Imo, best solution is used trigger which is cleaner because you can keep the chainable plugin system.
You can declare event handler in your plugin declaration and trigger from outside:
(function($) {
$.fn.top_islides = function(){
this.on ('init_islides', function(){
setTimeout(function(){picmove()},300);
};
//.....
};
})(jQuery);
$( "button" ).click(function () {
$( "p" ).trigger( "init_islides");
});
DOC can be found here : http://api.jquery.com/on/

Categories

Resources