Dojo.query foreach accessing element value - ajax

I'm a newbie in Dojo framework, so I hope my question is not really dumb.
I have a link in my web page :
Delete
The variable "index" is well defined, no issue with that.
Then, I've written this piece of code to add an action to the onclick event on my link and a JS function to call before the submit :
dojo.query("a[name=supprimerEnfant_name]").forEach(function(element) {
Spring.addDecoration(new Spring.AjaxEventDecoration({
formId: "form_id",
elementId: element.id,
event: "onclick",
beforeSubmit: function(){
jsFunctionToCall(element.value);
},
params: { _eventId: "deleteEvent", fragments:"frag"}
}))
});
In my jsFunctionToCall, I can get the element.id (checked and it's OK) but the element's value is null and I can't figure out why.
I'm probably missing something important, could you help me with that ?
Thanks in advance.

You should be aware that element.value only works with elements where it's part of the DOM, defined by W3C. So, if you look at the HTMLInputElement interface (used by form elements), you will see that it clearly has a property called value, referencing to the the value of the element.
However, the same is not true for an HTMLAnchorElement. This means the proper way to retrieve the value of the value attribute, is by selecting the attribute itself, using the getAttribute() function or by using the the dojo/dom-attr Dojo module.
For example:
require(["dojo/query", "dojo/dom-attr", "dojo/domReady!"], function(query, domAttr) {
query("a").forEach(function(element) {
console.log(element.id);
console.log(domAttr.get(element, "value")); // This will work
});
});
Demonstration: JSFiddle

The dojo query will return the domNode references always. Anyhow, the anchor element is a HTML element. So, this is nothing to do with Dojo and lets see whats wrong with the JS part.
The "value" is not a standard attribute of anchor element. So, the additional attributes need to be accessed using "getAttribute" method.
i.e. in your case,
element.getAttribute('value')

Related

Updating jQuery custom content scroller

I have one problem with jQuery custom content scroller when I try to manipulate elements on page via ajax queries.
$(window).load(function(){
$(".scroll").mCustomScrollbar({
scrollButtons:{
enable:true
}
});
});
then I execute one ajax query to populate data from server
$.get(url, {'count':count, 'type':type}, function(data) {
masBlock.append(data);
$(".scroll").mCustomScrollbar("update");
deleteHoliday();
saveHoliday();
$('.add-holiday').hide();
})
but method "update" doesn't work and scroller doesn't resize. Please, what should I do to avoid this problem.
Thank you in advance.
Does the masBlock variable define the .scroll element or an element inside it?
Do you load images or plain text?
Instead of using the update method, you could try setting updateOnContentResize option parameter to true and see if that helps:
$(window).load(function(){
$(".scroll").mCustomScrollbar({
scrollButtons:{
enable:true
},
advanced:{
updateOnContentResize:true
}
});
});

jQuery - How to call/bind jquery events for elements added by ajax?

I'm working on an implementation of the jQuery plugin Tag-it! with a product entry form for assigning attributes to products of different type (laptops, tv's, gadgets etc).
The concept is the following:
When adding a new product, first, the user selects the product category from a dropdown for the product being added and a jQuery .change() event is triggered making an ajax call to get all the attributes that are related to that category. For example, if Im adding a TV i want my ajax call to populate 3 inputs for inches, panel type, hdmi whereas, if i'm adding a laptop I want those inputs to be cpu, ram, hdd, screen etc. Tag-it! works with a list of words (in my case, attributes) and an input field for choosing the set of words.
In my case, for each type of attributes I want to populate a separate input field and assign/bind it to/apply tagit plugin (sorry, I dont know how else to explain it).
Javascript:
<script src="../js/tag-it.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function(){
// Sample1: var sampleTags1 = ["red", "green", "blue"];
// Sample2: var sampleTags2 = ["lcd", "plasma", "tft"];
var sampleTags1 = [<?=createTags('name', 'tags', 1)?>];
// createTags($name, $tags, $id) is a PHP function that returnss a list of tags for a given attribute
// Question 1: how do I place this here after a new input is added to the DOM?
$('#myTags').tagit();
//Question 2: for each input added to the DOM I need also to add this block in the javascript:
$('#allowSpacesTags1').tagit({itemName: 'item1', fieldName: 'tags1',
availableTags: sampleTags1, allowSpaces: true
});
$('#removeConfirmationTags').tagit({
availableTags: sampleTags,
removeConfirmation: true
});
});
$(document).ready(function() {
$('#cat_id').change(function(){
$.post('../includes/ajax.php', {
cat_id : $(this).find("option:selected").attr('value')}, function(data) {
$("#tagholder").html(data);
});
});
});
</script>
Ajax returns the following for each call:
<ul id="allowSpacesTags'.$row['ctid'].'"></ul> // $row['ctid'] is the ID for that attribute
which represents the input field for entering the tags/attributes.
Before there's any misunderstanding, I'm not asking how to do this in PHP.
My question is about the way I can dynamically add a var like sampleTags1 and also call the tagit() for each new input that is added to the DOM by ajax. I'll try to give any required information if my question isn't clear enough.
Please look at the questions in the code comments. Thanks!
http://api.jquery.com/live/
with .live( events, handler(eventObject) )
you don't need to attach or re-attach events when content is added dynamically
EDIT
i've just notticed that live is deprecated, instead you should use
.on()
http://api.jquery.com/on/

jQuery Delegate not binding like I want it to

Using jQuery 1.7
I'm having trouble binding a Click event to some dynamically loaded content.
I've looked around, tried .live, .delegate and .on, and I just can't get it to work.
This is my code:
$(".fileexplorer_folderdlg").delegate(".delete", "click", function () {
console.log("Hello world!");
});
The thing is, .fileexplorer_folderdlg is dynamically loaded. If I use .fileexplorer (not dynamically loaded), it works, but I have more elements with the .delete class that I do not wish to bind to (and neither element classes can be renamed or changed for various reasons).
I also tried using .fileexplorer_folderdlg .delete as the .delegate selector, didnt work either!
Of course I could just add another unique class to the elements I wish to bind to, but this really should work, right?
I believe this would work:
$(document).on('click', '.delete', function() {
if ($(this).closest('.fileexplorer_folderdlg').length) {
console.log('hello, world!');
}
});
or even just:
$(document).on('click', '.fileexplorer_folderdlg .delete', function() {
console.log('hello, world!');
});
As you've found, you can't bind on .fileexplorer_folderdlg because it's dynamic. You therefore need to bind on some static element that will contain that element at some point in the future.
Instead, this binds on the document (but will unfortunately fire for every single click on the document thereafter).
EDIT by Jeff
Although the code above did not work, modifying it a bit did the job, although not the most desirable solution.
$(document).on('click', '.delete', function () {
if($(this).closest(".fileexplorer") != null)
console.log("Thanks for your help!");
});
It works, but this event is fired for all other .delete classes, of which there are many. What I do not understand though, is why using .fileexplorer_folderdlg .delete did not work!

how to fake a click on a dynamic element?

On a static element, to fake a click, I use
$(selector).click();
But how can I do the same thing on a dynamic element (resulted from an ajax call)?
The same...:
$(selector).click();
Why didn't you try it first?
P.S. it is not called fake a click, it's called trigger the click event.
$(selector).trigger('click'); == $(selector).click();
Update
You need to bind that element a callback to the event in order it to work:
$(selector).click(function(){...});
$(selector).click();
If you want it to have the the click callback you assigned to the static elements automaticlly, you should use on\ delegate (or live but it's deprecated) when you attach the click callback.
$('body').on('click', 'selector', function(){...})
instead if body use the closest static element the holds that selector elements.
See my DEMO
within your ajax success function try your code:
$(selector).click();
Basing this on your previous question : How can I select a list of DOM objects render from an AJAX call?
$(document).ready(function(){
var listItems = $('#myList li a');
var containers = $('#myContainer > div');
listItems.click(function(e){//do someting
});
etc...
If the elements you are trying to attach a click handler to are supposed to be inside any of the two variables above then you WILL have to update those variables after the elements are inserted into the DOM, as it is right now only elements that exists during first page load will be inside those variables.
That is the only reason I can think of why something like :
$(document).on('click', listItems, function(e) {//do something
});
will not work!
Don't know if I understand (I'm french sorry...)
But try :
$(selector).live('click',function(){}); // deprecated it seems
Demo of gdoron with live() : http://jsfiddle.net/Rx2h7/1/
use on() method of jquery,
staticElement.on('click', selector, function(){})
on method generates click event on dynamically created element by attaching it to the static element present in the DOM .
For further reference check this out -- https://api.jquery.com/on/

Grails ; remoteFunction with dynamical update cause null in HTML page

I have an issue concerning the use of a remoteFunction component in java script function ; I am using Grails 1.3.7.
I have few div in a page which contain a div I want to update. Each div I want to update has its own id (fullUrlSaProfilDivX) where X is and unique ID in the page.
I want to update two div (one after one).
I created a java script function :
<g:javascript>
function removeSelectedProfilAssoc(urlSaId, profilAssocId) {
${ remoteFunction (action:"delete", update:'fullUrlSaProfilDiv'+urlSaId, controller:"profilAssoc", params:'\'id=\'+profilAssocId', options:[asynchronous:false]) };
${ remoteFunction (action:"listUrlSaProfil", controller:"profilAssoc", update:'lightUrlSaProfilDiv'+urlSaId, params:'\'urlSa.id=\'+urlSaId') };
};
</g:javascript>
Called by a link :
I want to update the div linked with the button (linkage with unique id).
I can't figure out why in the generated page I got null instead of the id and the div is not refresh :
function removeSelectedProfilAssoc(urlSaId, profilAssocId) {
new Ajax.Updater('fullUrlSaProfilDivnull','/_Pong2WAR/profilAssoc/delete',{asynchronous:false,evalScripts:true,parameters:'id='+profilAssocId});;
new Ajax.Updater('lightUrlSaProfilDivnull','/_Pong2WAR/profilAssoc/listUrlSaProfil',{asynchronous:true,evalScripts:true,parameters:'urlSa.id='+urlSaId});;
};
Am I doing something wrong ? How can I pass the id of the div I want to refresh and add it refreshed ?
Thank you for having a look !
Benjamin
ahah, you are mixing up javascript and gsp. I did it many times also, it can be tricky to find out!
In your case urlSaId is a javascript var, but you are using it in a GSP function call so it will be null....
Unfortunatly the workaround is not easy since the remoteFunction won't let you concatenate properly the javascript variable in the update since what you want is:
new Ajax.Updater('fullUrlSaProfilDiv'+urlSaId,'/_Pong2WAR/profilAssoc/delete',{asynchronous:false,evalScripts:true,parameters:'id='+profilAssocId});
What i suggest is to build directly this Ajax.Updater(..) without the use of remoteFunction (or something similar):
<g:javascript>
function removeSelectedProfilAssoc(urlSaId, profilAssocId) {
new Ajax.Updater('fullUrlSaProfilDiv'+urlSaId,'${createLink(action:"delete", controller:"profilAssoc")}',{asynchronous:false,evalScripts:true,parameters:'id='+profilAssocId});
new Ajax.Updater('lightUrlSaProfilDiv'+urlSaId,'${createLink(action:"listUrlSaProfil", controller:"profilAssoc")}',{asynchronous:true,evalScripts:true,parameters:'urlSa.id='+urlSaId});;
};
</g:javascript>
On a side note now, i am always using jquery instead, it simplifies all ajax in your GSP.
replace remoteFunction by
jQuery.ajax({
type:'POST',
data:'territorio='+territorio_id+'&anho='+anho+'&id='+firstIndicador+'&div='+divId+'&divmap='+divmap,
url:'/observatoriograils/eje/indGeneralporAnhoyTerritorio',
success:function(data,textStatus){jQuery('#'+divId).html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}});
where data are the parameters, url is /url/controller/function and divId is the name of div for update

Resources