Change element style after .get() success - javascript

I'm new to JS. I'm trying to change button's background-color after .get() success.
Here is example: http://jsfiddle.net/csTpG/95/
What's wrong with my code?
$('.add').click(function() {
var productID = $(this).attr('name');
$.get('/',{item_id : productID}, function() {
$(this).addClass('clicked');
});
return false;
});
<button class="add">click me</button>

Your button has no name attribute.
Aside from that, reference the clicked element outside the $.get callback to use it in the callback:
$('.add').click(function() {
var productID = $(this).attr('name');
// keep a reference to the element in this scope
var self = this;
$.get('/',{item_id : productID}, function() {
// use the reference in the callback
$(self).addClass('clicked');
});
return false;
});

Inside the $.get callback, this is not your element. You need save a reference to this first.
$('.add').click(function() {
var $this = $(this),
productID = $this.attr('name');
$.get('/',{item_id : productID}, function() {
$this.addClass('clicked');
});
return false;
});

Related

Conditional addClass not working for each elements with same class

Les say I have some buttons with same class. On page load I am checking some value using ajax for each button. Depending on returned value of ajax request I want to add some class to the buttons, but it is not working,
$(document).ready(function(){
$('.add-remove-permissoion').each(function(){
var child = $(this).val();
var parent = $('#parent-name').text();
$.get('my-url', function(data){
if(data == 1){
$(this).addClass('glyphicon glyphicon-ok');
}else{
$(this).addClass('emptybox-blank');
}
});
});
});
I have checked that my ajax request is returning correct data. What is that I am doing wrong here?
The problem is the this reference inside the ajax callback, in the success callback this refers to the jqXHR object not the dom element reference that is why it is not working.
You can use a closure variable as given below to fix the problem
$(document).ready(function () {
$('.add-remove-permissoion').each(function () {
var $this = $(this),
child = $this.val();
var parent = $('#parent-name').text();
$.get('my-url', {}, function (data) {
if (data == 1) {
$this.addClass('glyphicon glyphicon-ok');
} else {
$this.addClass('emptybox-blank');
}
});
});
});
this in the context of the $.get handler doesn't refer to the element of the current iteration. Each function has it's own this value. You have several options.
Use the second parameter of the each callback.
$('.add-remove-permissoion').each(function(index, element) {
Use $.proxy or Function.prototype.bind method for setting the this value of the handler.
$.get('my-url', function(data) {
// ...
}.bind(this));
Cache the this value of the each handler and use it in your $.get handler.
var elem = this;
$.get('my-url', function(data) {
// ...
$(elem)...
});
Also note that there is a syntax error in your code:
$.get('my-url'}, function(data){
// -----------^
Problem is $(this) within ajax call does not refer to the button clicked.
Replace $(this).addClass with myElement.addClass. Create myElement within click event just before the ajax call: var myElement = $(this).

send the img id to another file with ajax

I am trying to make this work, I have some images each one of them has this link with its own id.
this is the link: x
this is the script:
<script>
$(document).ready(function() {
$(".remove_img").click(function() {
e.preventDefault();
var id = $this.data('id');
$.ajax({
url: 'remove_img.php',
type: 'POST',
data: { bild : id },
success: function(data) {
alert("Gespeichert!");
}
});
});
});
</script>
and I receive the id in the remove_img.php like this: $_POST['bild']
in the chrome console I see this error:
$this is not defined (repetead 2 times)
You want to refer to the jQuery object correctly:
var id = $(this).data('id');
$this is read as a variable that hasn't been declared yet, whereas $(this) is the jQuery object wrapper for this, or the item that was clicked.
The current way to refer to the current jQuery element is $(this) not $this (your approach would work if that was a variable with the value of $(this) like var $this = $(this); which is valid but wouldn't make much sense in your case). So change this line:
var id = $this.data('id');
To:
var id = $(this).data('id');
Or (referring to the DOM element directly instead of using jQuery):
var id = this.dataset.id;

Removing an unbind on a button in jquery?

function getData(url) {
$.getJSON(url, function(result) {
$('#formNav ul').append('<ul/>')
$.each(result, function() {
var list = $('#formNav li'),
listItem = $('<li/>'),
html = listItem.append($('<h5/>').text(this.name));
$.each(this.items, function() {
listItem.append($('<a />').attr('href', this.id).text(this.name))
});
list.append(html)
});
});
};
$(function(){
var Menu = {
$menu: $('.config-nav #formNav'),
$trades : $(".config-nav select#tradesmanList"),
$skills : $(".config-nav select#jobList"),
init: function(){
var $menu = Menu.$menu;
// Set menu up
$menu.children("li").addClass('closed');
$menu.find(".js-reveal").hide();
Menu.$skills.attr("disabled", "disabled");
Menu.$trades.on("change", function($skills){
Menu.$skills.removeAttr("disabled");
});
// bind to click on the item...
$menu.on("click", "h4", this.toggle);
},
toggle: function() {
// Toggle the hide show of the drill down menu
var $this = $(this),
$category = $this.parent();
console.log($this.parent().index());
var data = getData("test.json");
$category.addClass("loading").toggleClass("open");
$this.next(".reveal").delay(100).toggle(0, function(){
$category.Data;
$category.removeClass("loading");
});
}
};
Menu.init();
});
I have a function that returns json data , i then call this function in the Menu function to display the data however every time i click the button the data just keeps being generated instead i want it to display the data and then once it is clicked again hide the data? if anyone has any advice that would be great.
Thanks.
When ever you call the toggle function You seem to get the data using
var data = getData("test.json"); and then use it to populate the list..
Why don't you move the getData method to outside the toggle function and instead move it to to init function .. Look's like it should be fine then..

dynamically change function name in javascript

$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, marker2); // I need instead of 2 to print the value of variable id
});
How can I dynamically change the number 2 to variable ID ?
Thanks for any help
Don't use eval, use a hash:
var markers = {
"key1": function(){},
"key2": function(){},
"key3": function(){}
};
$('a').live('click',function(e){
e.preventDefault();
var id = this.id; //Use this.id instead of attr
infowindow2.open(map, markers[id]);
});
Instead of using eval, - better change you data structures:
var markers = {
'1': function () { doStuff(); },
'2': function () { doOtherStuff(); },
}
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, markers[id]);
});
I think it would be easier to write a new function with a switch. I can't recommend using eval.
EVAL should always be the last option
In order use dynamic name in a function names you can windows object.
Here is an Example:
var id = '2';
function map2() {
alert('me called');
}
window["map"+id]();
Demo
Your Usage would be something like this
$('a').on('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, window['map'+id]());
});
$('a').live('click',function(e){
e.preventDefault();
var id = $(this).attr('id');
infowindow2.open(map, eval('marker' + id));
});
LIVE DEMO
Notes:
eval is deprecated, You should look for a better design.
so as live... You should use on instead.

How do I pass the this element to the result of getJSON?

I want to do the following...
$('.showcomments').click(function() {
$(this).parent().hide();
jQuery.getJSON('comments.json', function($data) {
$(this).parent().append($data['value'])
//this is meant to be the instance of
//$('.showcomments') that has been clicked
});
});
the problem is that the callback of getJSON of course did not inherit the this item... but how do I do what I am intending?
Reference it in a variable:
$('.showcomments').click(function()
{
var $th = $(this); // References the clicked .showcomments
$th.parent().hide();
jQuery.getJSON('comments.json',function($data)
{
$th.parent().append($data['value']); // will reference the correct element
});
});

Categories

Resources