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
Related
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;
})
} );
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
I have this JQuery expression where i push a button, get some HTML from the server and then append it to a DOM node in my document:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").click(function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
});
});
});
</script>
I have multiple ".addButton" buttons on my web site. The problem im experiencing is that after multiple clicks on the buttons my .done handler is being called multiple times.
My guess is that i have a list of event handlers that are being executed, I cant understand where / why this is done or how I prevent it from happening.
The problem is not taht you do the request is done more then once rathern then it calls done after its done.. you can keep the state in data object::
$(document).ready(function () {
var posting = false;
$(".addbutton").data("done", false).click(function () {
var addbuttonNode = $(this);
if (!addbuttonNode.data("done")) {
addbuttonNode.data("done", true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data);
});
}
});
});
I would do the following:
$(".addbutton").click(function () {
var addbuttonNode = $(this);
addbuttonNode.attr('disabled',true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
addbuttonNode.attr('disabled',false);
});
});
You could check it for any request pending:
$(document).ready(function () {
$(".addbutton").click(function () {
// if any request pending, return {undefined}
if ($.active) return;
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
If you wish instead each button to be clickable only once, then use jQuery .one() method:
$(document).ready(function () {
$(".addbutton").one('click', function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
Try to use bind, and unbind functions for the event handling. Then You can unbind the click function after it was executed once.
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").bind('click',function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
addbuttonNode.unbind('click');
});
});
</script>
Another way of doing nearly the same, I think this should be better:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").each(function(){
$(this).bind('click',function () {
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
$(this).unbind('click');
});
});
});
</script>
I haven't tried it yet, but it should work, try it! :)
You can also set up a class or data attribute to check if the button was already clicked. You can then exit from the script like if($(this).hasClass('clicked')) { return; } or something...
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');
}
});
I am trying to use the value of a drop list as the the name of the next function. The string is correct and shows in an alert. Also writing the name explicitly in the code does work. But using parts from the variable in the scope of both functions does not work at all.
Drupal.behaviors.smart_inventory = {
attach: function(context, settings) {
// this should be in the scope of both functions
var selecttype;
$('#select-voc-content_types', context).change(function () {
contenttype = $( this ).val();
secondary = $('#' + contenttype);
if($(secondary).length > 0)
{
// set the select list. tried an alert and the variable string is set
selecttype = '#select-voc-' + $( this ).val();
$('.group-types').show();
$('#' + contenttype).show();
$('#object-ajax-form').hide();
}
else
{
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": contenttype }, frmDrupal);
}
});
// this does not respond as jquery does not accept the string as an element name
// or maybe the variable is not available here?
$( selecttype, context ).change(function () {
var nodetype = $( this ).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal);
});
var frmDrupal = function(responseText) {
$('#object-ajax-form').show();
$('#object-ajax-form').html(responseText);
$('#object-node-form-message').hide();
}
}
};
If found that this works! But is nesting a function good practice? or good enough? ;
Drupal.behaviors.smart_inventory = {
attach: function(context, settings) {
var selecttype;
$('#select-voc-content_types', context).change(function (selecttype) {
contenttype = $( this ).val();
secondary = $('#' + contenttype);
if($(secondary).length > 0)
{
// set the select list
selecttype = '#select-voc-' + $( this ).val();
$('.group-types').show();
$('#' + contenttype).show();
$('#object-ajax-form').hide();
}
else
{
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": contenttype }, frmDrupal);
}
$( selecttype , context ).change(function () {
var nodetype = $( this ).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal);
});
});
Your selecttype variable is not even set yet when you try to use it - it will only get set when the change handler on the element with id select-voc-content_types is triggered.
The problem is that the variable doesn't have a value at the time that the handler is attached. The easiest way to handle it is using the attribute "starts with" selector to match all possible select types rather than trying to apply a handler per select type. You could then use the chosen select type to filter within the handler as needed.
$('[id^="select-voc-"]',context).change( function() {
if (this.id == selecttype) {
...
}
else {
return false; // this isn't the correct select type, prevent the action
}
});
//selecttype changes during an event fire. event registration happens way before then. just do this.
$( '[id^="select-voc-"]', context ).change(function () {
var nodetype = $( this ).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal);
});
// depending on your version of jQuery, go for .on wherever possible:
$(context).on({
'change':function(evt){
var nodetype = $( this ).val();
$('#object-node-form-message').show();
$.post('smart_inventory/ajax', { "node-type": nodetype }, frmDrupal)}
},'[id^="select-voc-"]','');