How can I reference specific DOM element to specific JS object?
For example, i have an array of customers. Using jQuery, for each customer I create LI with checkbox and span for customers name. When checkbox is clicked, I need to do some processing on that customer JS object. The question, how i can get this JS object an easy way.
Currently I have following:
$(customers).each(function(){
$("<li>").append($("<input type=\"checkbox\"").attr("id","chk_" + this.ID)).append($("<span>").text(this.Name)).appendTo("#ulCustomers");
});
$("#ulCustomers input[type=checkbox]").bind("click",function(){
var customerId = $(this).attr("id").replace("chk_","");
var CustomerObj = $(customers).filter(function () { return this.ID == customerId }).get(0);
myProcess(CustomerObj); //Two above two lines are just for select correct customer from array.
});
I believe in world of JS and jQuery exists more elegant way to do it.
Thanks
You can use jquery data function
$(customers).each(function() {
var elem = $("<li><input type='checkbox'><span>" + this.Name + "</span></li>").appendTo("#ulCustomers");
elem.find("input").data("customer", this);
});
$("#ulCustomers input[type=checkbox]").click(function() {
var CustomerObj = $(this).data("customer");
myProcess(CustomerObj);
});
Could you not bind the click event to a closure with a reference to the relevant Customer object?
like this
$(customers)
.each(function(){
var custObj = this;
$("<li>")
.append(
$("<input type=\"checkbox\"")
.append($("<span>")
.text(this.Name))
.appendTo("#ulCustomers")
.bind("click", function(){
myProcess(custObj);
})
});
I would use jQuery data, just like this:
$("checkbox").data('customer', this.ID);
To retrieve the data:
$("#ulCustomers input[type=checkbox]").bind("onchange",function(){
var customerId = $(this).data("customer");
var CustomerObj = $(customers).filter(function () { return this.ID == customerId }).get(0);
myProcess(CustomerObj); //Two above two lines are just for select correct customer from array.
});
Additionally, don't use click event on check-boxes, use onchange event ;)
Related
Looked for the answer all over, tried reading seperatly but couldn't find an answer..
I have a site, on which Google Tag Manager is implemented, and I need to extract the id of a clicked button (or its parent).
this is my code:
function(){
$(document).ready(function(){
var editid;
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
return editid;
});
}
Thanks!
The simplest approach is to create the following custom javascript variable:
function(){
return $({{Click Element}}).attr('data-id');
}
This will return the data-id attribute for all events (including clicks).
Attach this variable to the relevant event tag, and use click class contains uk-button as the trigger.
You can remove the outer function and code like below.
$(document).ready(function () {
$('div.uk-button').click(function () {
var editid;
editid = $(this).attr('data-id');
alert(editid);
});
});
Hey it looks like you may be not be catching the returned value of the document ready callback.
For example, this returns undefined since the return of $(document).ready() callback is not being returned by the containing function:
function testfunc() {
$(document).ready(function(){
var editid = 'this is the return value';
return editid;
});
}
testFunc()
"returns undefined"
I'm guessing that you might be trying to set up a custom javascript variable in GTM. You can still use document ready to ensure the elements are present but the returned value needs to be returned by the outer function for it to be passed into the variable.
So your example should work as follows:
function(){
var editid;
$(document).ready(function(){
$('div.uk-button').click(function() {
editid = $(this).attr('data-id');
});
});
return editid;
}
I've the following snip of a code:
var about = "about.html";
function loadPage(target){
$("#dashboard").load(target);
}
$(".nav li").click(function(){
loadPage($(this).attr("class"));
});
So when I click on a button like <li class="about">, target is = about.
But in that way, $("#dashboard").load(target); doesn't load the variable about which is the html-file which I want to load.
So how is it possible to call the variable in this way?
You seem to miss the .html part. Try with
$("#dashboard").load(target+'.html');
But, supposing you have only one class on your li element, you'd better use this.className rather than $(this).attr("class").
EDIT :
if you want to use your about variable, you may do this :
$("#dashboard").load(window[target]);
But it would thus be cleaner to have a map :
var pages = {
'about': 'about.html',
'home': 'welcome.jsp'
}
function loadPage(target){
$("#dashboard").load(pages[target]);
}
$(".nav li").click(function(){
loadPage(this.className);
});
A stupid answer : create a <a> tag, and set its href attribute to the correct value.
Otherwise :
A standard way to store key: values pairs in javascript is to use a plain object :
var urls = {};
urls['about'] = 'mysuperduperurlforabout.html';
function loadPage(target) {
var url = urls[target];
//maybe check if url is defined ?
$('#dashboard').load(url);
}
$(".nav li").click(function(){
loadPage($(this).attr("class") + ".html");
});
or
$("#dashboard").load(target+".html");
You can call the variables like this (if that's what you asked):
var test = 'we are here';
var x = 'test';
console.log(window[x]);
It's similar to the $$ in PHP. The output will be:
we are here in the console window.
You could put the "about" as an object or array reference similar to:
var pageReferences = [];
pageReferences["about"] = "about.html";
var otherReference = {
"about": "about.html"
};
function loadPage(target) {
alert(pageReferences[target]);
alert(otherReference[target]);
$("#dashboard").load(target);
}
$(".nav li").click(function () {
loadPage($(this).attr("class"));
});
Both of these alerts will alert "about.html" referencing the appropriate objects.
EDIT: IF you wished to populate the object based on markup you could do:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + ".html";
});
});
You could even store the extension in an additional attribute:
var otherReference = {};
$(document).ready(function () {
$('.nav').find('li').each(function () {
var me = $(this).attr('class');
otherReference[me] = me + "." + $(this).attr("extension");
});
});
Better would be to simply put the page reference in a data element:
<li class="myli" data-pagetoload="about.html">Howdy</li>
$(".nav li").click(function () {
loadPage($(this).data("pagetoload"));
});
I am creating list of <span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service">'+servicename+'</a><br/></span> tags dynamically and appending it to a div
Then using the below map to map a tags attribute to some function
var idMap = {
//it can be a lot more
"javaInfo":javaInfo,
/*infa9 product map*/
"infa9PMServer":infa9PMServer,
"infa9Service":infa9Service
};
This is the click Handler
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
treeItemClickHandler(elementId);
});
function treeItemClickHandler(id)
{
(idMap[id])(id); //Is this usage called 1st class functions?
}
function infa9Service(id)
{
alert("i got this "+id);
}
Note: I am using Jquery v1.6.3
But when I click on any of the a tags, it calls the function an does all the operation inside the function, but gives an error Object dosen't support this porperty or method in the treeItemClickHandler function.
I would like to know,
How to avoid getting this error?
Is there a more better approach for something like this?
And Is it 1st class functions that I am using (if so where can i learn more about it)?
Thanks.
Update
How can I pass 2nd parameter?
'<span class="infa9span"><img src="/csm/view/include/images/foldericon.png"/><a id="infa9Service" title='+servicename+'>'+servicename+'</a><br/></span>'
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
var elementName=$(this).attr("title");
treeItemClickHandler(elementId,elementName);
});
function treeItemClickHandler(id,name)
{
idMap[id](id,name);
}
function infa9Service(id,name)
{
alert(id+", "+name);
}
It gives me infa9Service, undefined
check this out http://jsfiddle.net/ywQMV/4
1)define your functions.
2)define your id map.
html part :
<div id ="ds-accordion">
<span class="infa9span">
<img src="/csm/view/include/images/foldericon.png"/>
<a id="infa9Service" title='+servicename+'>'+servicename+'</a>
<br/>
</span>
js part:
function infa9Service(id, serviceName)
{
alert("i got this "+id +" serviceName : " + serviceName);
}
var idMap = {
"infa9Service":infa9Service
};
$('#ds-accordion a').click(function(event) {
var elementId=$(this).attr("id");
var serviceName = this.title;
treeItemClickHandler(elementId, serviceName);
});
function treeItemClickHandler(id,serviceName)
{
// alert(idMap[id])
(idMap[id])(id,serviceName); //Is this usage called 1st class functions?
}
What I'm trying to achieve, is to output a json list that contains a list of Css classes, and their corresponding url records, i.e.
var jsonList = [{
"CSSClass": "testclass1",
"VideoUrl": "/Movies/movie.flv"
}, {
"CSSClass": "testclass2",
"VideoUrl": "/Movies/movie2.flx"
}]; //]]>
foreach item in the list I am adding a click event to the class...
$.each(script, function() {
$("." + this.CSSClass, "#pageContainer").live('click', function(e) {
videoPlayer.playMovie(this);
return false;
});
});
What I'm wondering, is if I can somehow get the corresponding url from the jsonlist, without having to loop through them all again, searching for CSSClass, or adding the url to the link as an attribute?
you can add an Index and an Item parameter to the callback function in $.each method.
$.each(script, function(i, item) {
$("." + item.CSSClass, "#pageConainer").live("click", function() {
videoPlayer.playMovie(item.VideoUrl);
return false;
});
});
"i" will be a counter of each iteration within the json object
"item" will represent the object in use
Absolutely, you just need to capture the your object so that the click function's closure has access to the right thing when it fires. Something like this should work:
$.each(script, function() {
var vid = this;
$("." + vid.CSSClass, "#pageContainer").live('click', function(e) {
videoPlayer.playMovie(vid.VideoUrl);
return false;
});
});
I am using jquery to add mulitple new "addTask" form elements to a "ul" on the page every time a link is clicked.
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
saveTask();
});
These new nested ul elements all have an button with the same class "saveTask". I then have a function that allows you to save a task by clicking on an button with the class "saveTask".
// Save New Task Item
function saveTask() {
$('.saveTask').click(function() {
$this = $(this);
var thisParent = $this.parent().parent()
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
}
This essentially allows the user to enter some text into a form input, hit save, and then the task gets saved into the database using ajax, and displayed on the page using jQuery.
This works fine when there is only one element on the page with the class "saveTask", but if I have more than 1 form element with the class "saveTask" it stops functioning correctly, as the variable "var task" shows as "undefined" rather than the actual value of the form input.
Don't rely on the .parent() method. Use .closest('form') instead. So the following line:
var thisParent = $this.parent().parent()
should look something like this instead:
var thisParent = $this.closest('form');
EDIT:
Based on the updated information you provided, it looks like when you're trying to register the click event handler it's failing out for some reason. Try this javascript instead as it will make use of the live event so that all the newly added items on the page will automatically have the click event autowired to them.:
$(function(){
$('span a').click(function(e){
e.preventDefault();
$('<li>\
<ul>\
<li class="sTitle"><input type="text" class="taskName"></li>\
<li><input type="button" value="saveTask" class="saveTask button"></li>\
</ul>\
</l1>')
.appendTo('#toDoList');
});
$('.saveTask').live('click', function() {
$this = $(this);
var thisParent = $this.closest('ul');
// Get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save',
data, function(data) {
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
});
First turn the save task into a function:
(function($){
$.fn.saveTask= function(options){
return this.each(function(){
$this = $(this);
$this.click(function(){
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
});
});
return false;
})(jQuery)
When the app starts change the saveTask selector to this:
function saveTask(){
$('.saveTask').saveTask();
}
Then on your add function:
function addTask(){
$newTask = $("<div>Some Task stuff</div>");
$newTask.saveTask();
}
This code is written very quickly and untested but essentially create a jQuery extension that handles for data submission then when ever a task is created apply the save task extension to it.
I think you're looking for the live event.
Also, your code is a little awkward, since the click event is only added when the saveTask() function is called. In fact, the saveTask() function, doesn't actually save anything, it just adds the click event to the elements with the .saveTask class.
What is your HTML structure?
It looks like your code can't find the input.taskName element.
Try setting thisParent to something like $this.closest('form'). (Depending on your HTML)
You could try wrapping your click function in an each()
ie
function saveTask(){
$('.saveTask').each (function () {
$this = $(this);
$this.click(function() {
var thisParent = $this.parent().parent()
//get the value
var task = thisParent.find('input.taskName').val();
// Ajax Call
var data = {
sTitle: task,
iTaskListID: 29
};
$.post('http://localhost:8501/toDoLists/index.cfm/Tasks/save', data, function(data){
var newTask = '<a>' + task + '</a>'
thisParent.find('li.sTitle').html(newTask);
});
return false;
});
})
}
I find this helps sometimes when you have issues with multiple elements having the same class