How to save "title" attribute of "a" with jQuery? - javascript

How can I save the value of the title for a row? These are the values of the title=%s:
<a class="false" title=1106 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1153 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
<a class="false" title=1175 href="/useradminpage?main_id=%s&display=false"><span class="small">(hide)</span></a>
...
I've tried countless variations but none of them work. This is what I have now:
<script>
$(document).ready(function() {
console.log("ready");
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = a.title;
var display = "false";
e.preventDefault();
});
$("a.false").click(function() {
$.ajax({
url: "/useradminpage?main_id=%s&display=false",
data: {main_id: "main_id", display: "display"},
success: function(data) {
display_false()
alert("4 - returned");
}
});
});
});
</script>
This is the third question on this topic. I appreciate any help. Thanks.

instead of
var main_id = a.title;
try
var main_id = $(this).attr('title');
because if I'm not wrong, "a" isn't defined

I think what you're trying to do is pass the value of the title attribute along in your AJAX request. If that's the case, the easiest thing to do will be to do it all in one event handler (is there a reason you're binding 2 different handlers to the same event?):
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title;
var display = "false";
e.preventDefault();
$.ajax({
url: "/useradminpage",
data: {main_id: main_id, display: display},
success: function(data) {
display_false();
alert("4 - returned");
}
});
});
Your problem currently is that main_id and display are not in the scope of the second event listener, so will be undefined (and they shouldn't be quoted, otherwise you're just passing in strings). As you're passing in a data object to the ajax function, you don't really need to add the query string to the URL either.
Aside from that, when you assign a value to main_id, you're using a.title. In this case a is undefined, and you will need to use this, which will be a reference to the clicked element.

I suspect that I might be missing something, but I suspect that your problem is using a.title instead of this.title:
$("a.false").click(function(e) {
$(this).closest("tr.hide").hide("slow");
var main_id = this.title; // or you could use the jQuery object approach: $(this).attr('title') instead
var display = "false";
e.preventDefault();
});
The problem in your original approach is that a would be parsed as a variable, which hasn't been assigned a value, nor has it been declared, so that it would return undefined or null (at best). Within the scope of the each() method, you're iterating over individual nodes; so to access the properties/attributes of that node use this.

To access any attribute of a DOM element through jQuery, you can use the .attr() function.
In your particular case you would do.
var main_id = $(this).attr('title');

Related

PHP OnClick Returning undefined

I've got a while loop to build a table of data and onclick I want to call a function but when I the function is called it's not getting the info from the onclick being passed.
HTML:
echo "<td width='25%' align='center'><a href='javascript:void(0)' id='{$row['id']}' class='{$row['status']}' onclick='hello()'> {$row['status']} </a></td>";
JS:
//onclick function
function hello()
{
// Get the ID of the button that was clicked on
var id_of_status_to_update = $(this).attr("id");
var status_to_be_updated = $(this).attr("class");
var varData = 'id=' + id_of_status_to_update + '&UserStatus=' +
status_to_be_updated;
console.log(varData);
// Make an AJAX request
$.ajax({
url: "php/processor.php", //This is the page where you will handle your SQL insert
type: "POST",
data: varData, //The data your sending to processor.php
async: false,
success: function(){
// location.reload();
alert("Hello Function");
},
error: function(){
alert("There was a problem, please try again or contact the admin for assistance.");
}
});
};
but when I check the console log I'm seeing the id and userstatus are undefined instead of what should be the passed attributes of id and class. Any help? I know the function is being called properly because I'm getting the success alert.
To fix your undefined issue, remove the ancient onclick method, and use a proper jquery .click event handler, and then your use of $(this) will work properly.
First adjust your html build to this:
echo "<td width='25%' align='center'><a href='#' id='{$row['id']}' class='clicker {$row['status']}'> {$row['status']} </a></td>";
Then adjust the javascript a bit to this:
$(document).ready(function() {
$(".clicker").click(function(e){
e.preventDefault(); // new line to stop the anchor click default behavior
var id_of_status_to_update = $(this).attr("id");
var status_to_be_updated = $(this).attr("class");
// ... the rest you had is fine as is ...
});
});
This attaches a click event handler to the class if "clicker", so it applies to all buttons with that class.
Use this instead:
$('#id').on('click', function(){
//Do something
//console.log(this)
})
Of course you would need to pass the element a fixed id, alternatively you can use $('.class') and pass it a class instead!
because the this inside function hello points to the window object. you can pass an event parameter to the hello function like onclick="hello(event)" and inside this function, you can use event.target.getAttribute('id') to access this element's id, don't forget to change the function definition function hello(){...} to function hello(event){...}

how to use this incomplete javascript object in HTML

I got this javascript code to solve in a manner to use inner function but not able to use it. Please try to help me to use inner functions or do i need to modify this. I want to use inner functions on click on html element such as view and remove respectively;
var App = function(){
var url = 'api';
function view(event) {
var id = '??'; //here i have to receive id of the element(data-id)
$.ajax({
url: url + '/view/' +id,
data: data
}).done( function (data){
});
}
function remove(event) {
var id = '??'; //please determine the id
$.ajax({
url: url + '/remove/' + id ,
data: data
}).done( function (data){
});
}
function initialize() {
//
}
return {
//
}
}();
Try doing this:
For id you can do one thing, Save the id in data-id attribute of the element on which you want onClick listener and access it using Event-Delegation in javascript.
To use the inner method you don't need to return anything. Just do it this way :
var App = function(){
var url = 'api';
function view(event) {
//access the id attribute of event.target
}
function remove(event) {
//same
}
function initialize() {
//
}
App.view = view;
App.remove = remove;
};
//EDIT : instead of making it self-invoking, call the app function
App();
//to access it outside:
App.view("your_parameter");
App.remove("your_parameter");
EDIT : Instead of making it self-invoking, call the app function
Well it's pretty simple, use the $("#caller").click() function of our beloved
jQuery
Then inside the .click() function you can easily retrieve your id
Here you can find more on the .click() function
It will be something like this
$( "#view" ).click(function() {
id = document.getElementById("id").id;
//Here paste the code of your view function
});

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).

Simplifying a jQuery functions

I was wondering the method of simplifying this script, because somehow I am repeating myself all over again...
$('.userprofile').click(function(){
card_profile.load(url_settings).dialog('open');
});
$('.cust-profile').click(function(){
card_profile.load(url_customer).dialog('open');
});
$('.my-profile').click(function(){
card_profile.load(url_my).dialog('open');
});
var obj = {
'.userprofile' : url_settings,
'.cust-profile': url_customer,
'.my-profile' : url_my
};
$.each(obj, function(sel, url) {
$(sel).click(function(){
card_profile.load(url).dialog('open');
});
});
or
$(".userprofile,.cust-profile,.my-profile").click(function() {
var url = $(this).hasClass("userprofile") ? url_settings :
$(this).hasClass("cust-profile") ? url_customer :
url_my;
card_profile.load(url).dialog("open");
});
This is somewhat better, but you can't get significant gain I guess:
$('.userprofile').data('url',url_settings);
$('.cust-profile').data('url',url_customer);
$('.my-profile').data('url',url_my);
$('.userprofile, .cust-profile, .my-profile').click(function(){
card_profile.load($(this).data('url')).dialog('open');
});
If you assign URL to every button, then you don't have to repeat the classes:
$('button').click(function(){
card_profile.load($(this).data('url')).dialog('open');
});
One way to do this would be to iterate over an array (or two) of strings.
Edit: declared i outside of for loop to address comment from #crazytrain
arr = ['user', 'cust', 'my'];
url_arr = [urlA, urlB, urlC];
var i;
for (i in arr){
$('.' + arr[i] + '-profile').click(function(){
card_profile.load(url_arr[i]).dialog('open');
});
}
$(document).on('click', function(e){
if($(e.target).hasClass('userprofile')){
card_profile.load(url_settings).dialog('open');
}
if($(e.target).hasClass('cust-profile')){
card_profile.load(url_costumer).dialog('open');
}
if($(e.target).hasClass('myprofile')){
card_profile.load(url_my).dialog('open');
}
It's a little better with a function:
$('.userprofile').click(function(){
loadDiag(url_settings);
});
$('.cust-profile').click(function(){
loadDiag(url_customer);
});
$('.my-profile').click(function(){
loadDiag(url_my);
});
function loadDiag(url){
card_profile.load(url).dialog('open');
}
You could also switch through the parameter and do multiple things per click
$('.my-profile, .userprofile, .cust-profile').click(function(){
card_profile.load(url).dialog('open');
});
Edit: on second thoughts - do what Eltier says.
Assign a url attribute to each element. Then you can retrieve that value and use in your code in this way.
$('.userprofile').attr('url',url_settings);
$('.cust-profile').attr('url',url_customer);
$('.my-profile').attr('url',url_my);
$('.my-profile, .userprofile, .cust-profile').click(function(){
var url = $(this).attr('url');
card_profile.load(url).dialog('open');
});
You could use the html data attribute and have it simple like this
$('.userprofile, .cust-profile, .my-profile').click(function(){
var url = $(this).attr('data-url');
card_profile.load( url ).dialog('open');
});
<div class="userprofile" data-url="settings.php">Settings</div>
And to make it even better you could add a class to all load items like this
$('.load-box').click(function(){
var url = $(this).attr('data-url');
card_profile.load( url ).dialog('open');
});
<div class="userprofile load-box" data-url="settings.php">Settings</div>
Throwing another hat in the ring here...
var links = [{profile: '.userprofile', url: url_settings, clickDialog: 'open'},
{profile: '.cust-profile', url: url_customer, clickDialog: 'open'},
{profile: '.my-profile', url: url_my, clickDialog: 'open'}];
function clickOpen(url,value) {
card_profile.load(url).dialog(value);
}
links.forEach(function(element) { $(element.profile).click(
clickOpen(element.url,element.clickDialog) });
You can save a parameter in de caller object and then do something like this:
$('.userprofile, .cust-profile, .my-profile').on('click',function(){
var parameter = $(this).data( 'parameter' );
card_profile.load( parameter ).dialog( 'open' );
});
You can find more information about storing data here, is very easy.

b.createDocumentFragment is not a function (jQuery)

I'm playing around with a function and getting
b.createDocumentFragment is not a function (jQuery)
My function is
function tweetCount(url) {
$.getJSON("http://urls.api.twitter.com/1/urls/count.json?url="+url+"&callback=?", function(data) {
count = data.count
$(this).append(count);
})
}
I've tried lots of different way but can't seem to find out why it doesn't like "append". "count" is a number and something like alert(count) works, but not append!
Any help?!
Alex
I don't think that this is referring to what you think it is. Change $(this) to an explicit reference to the DOM element you want.
Alternatively, you can define this by calling:
tweetCount.call($("#element"), url)
Edit
Try this:
$("span.tweetcount").each(function(){
url = $(this).attr('title');
tweetCount.call(this, url);
});
Or, to save space:
$("span.tweetcount").each(function(){
tweetCount.call(this, $(this).attr('title'));
});
Edit 2:
Try replacing tweetCount with this:
function tweetCount(url) {
var that = this;
$.getJSON("http://urls.api.twitter.com/1/urls/count.json?url="+url+"&callback=?", function(data) {
count = data.count;
$(that).append(count);
})

Categories

Resources