how to use this incomplete javascript object in HTML - javascript

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
});

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

Get id of the <a> tag from one function to another

I am very new in javascript/jQuery so please bear with me if my question will be too easy for you and too difficult for me.
This is from a function, I just don't post the complete codes since it will be too long.
And I have another function which also have an ajax and I want to pass get the ID of the <a> tag:
function someName() {
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'MyAction',
word: 'Wednesday',
count: '4',
page: '1'
},
success: function(data) {
var json = jQuery.parseJSON(data);
var htmlInfo = '';
for (i = 0; i < json.length; i++) {
var htmlCode = '';
htmlInfo = htmlInfo + htmlCode;
}
jQuery('#WMVideoxx').html(htmlInfo);
}
});
}
and
function VideoDiv() {
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'actionNameHere',
idorname: id //I Want to pass the ID here
});
}
What you are doing is:
jQuery('a').click(function() {
VideoDiv(jQuery(this).attr('id'));
});
This will not work because of the nature of <a> tag being dynamically generated and the event doesn't get registered. Consider delegating the event (see Understanding Event Delegation for more information):
jQuery(document).on("click", 'a', function() {
VideoDiv(jQuery(this).attr('id'));
});
The above code works, but will delegate for all the <a> inside the document. Instead, add a class or something that uniquely identifies that. And call it this way:
jQuery(document).on("click", 'a.class', function() {
VideoDiv(jQuery(this).attr('id'));
});
Another thing about the above delegation of code is, it is better to use a closest static parent instead of document. Since I don't know the HTML structure, I have used document. :)
Also, as Ismael Miguel says, it is better to get the id using this.id:
jQuery(".static-parent").on("click", '.class', function () {
VideoDiv(this.id);
});
The above would be the best code.
Also, it has been pointed out again, for better performance, you may replace the code with:
setTimeout(
(function () {
VideoDiv(this.id);
}).bind(this), 10
);
This will let jQuery handle the next even handler, and will execute this code on the next 10ms (when available).
use onclick="function();" with your anchor and pass arguments that you want in your function
Your htmlcode should be like this
Your VideoDiv function
function VideoDiv(id)
{
//your ajax goes here
}
Try this : you can put onclick call to a tag while creating it and pass this object which is nothing but the a tag element, see below code
var htmlCode = '';
Now make following changes in your javascript function
function VideoDiv(anchor)
{
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'actionNameHere',
idorname: anchor.id //pass id here from anchor object
}
});
}
NOTE: your data attribute in above ajax call is incomplete, please correct it.

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

Prevent previously requests on click

I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">
onclick of each i use next function:
function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();
var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
isParentools = 1;
var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;
$("#ratingModal").on("show.bs.modal", function (e) {
$.ajax({
url: url,
cache: false,
dataType: "html",
success: function (data) {
$("#ratingModal").find(".modal-body").html(data);
}
});
});
$("#ratingModal").on("hide.bs.modal", function (e) {
$(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');
return false;
}
By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);
Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.
Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
....
url = .....
}
$(function() {
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
});
However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);
In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
//retrieve the url from the modal
var url = $(this).data('table-url');
//use the url
$.ajax({ url: url, .... }):
});

jQuery function not attached to dom elements

I am trying build a web page that will construct elements from JSON file and attach click function to those elements.
$(document).ready(function(){
$.ajax({
url: 'database.php',
type: "POST",
dataType: 'json',
success: function (datas) {
(datas);
for (var x = 0; x < datas.data.length; x++) {
var id = datas.data[x].ID;
var ip = datas.data[x].IP;
var ips='<div class="ip"><span id="ids">'+id+'</span><span id="number">'+ip+'</span></div>';
$('#left').append(ips);
}
}
});
$('.ip').click(function () {
alert($(this).children('#ids').text());
});
});
the code above builds the elements successfully but the click function is not working.
You can use the on function instead, it is used to apply event handlers to elements that are not yet created.
Where you have your current click setup, try something like this instead:
$(document).on('click', '.ip', function(){
alert($(this).children('#ids').text());
});
As #Pete has suggested, it is not a good idea to assign the same id attributes within a loop, they should be unique to the document. Consider finding them via class names instead, so you could alert something like:
alert($(this).children('.MyIdsSpan').text());

Categories

Resources