jQuery - How to call/bind jquery events for elements added by ajax? - 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/

Related

Filling MVC DropdownList with AJAX source and bind selected value

I have view for showing Member details. Inside there is an EditorFor element which represents subjects taken by the member.
#Html.EditorFor(m => m.Subject)
Inside the editor template there is a Html.DropDownListFor() which shows the selected subject and button to delete that subject
I am using an Html.DropDownListFor element as :
#Html.DropDownListFor(m => m.SubjectID, Enumerable.Empty<SelectListItem>(), "Select Subject",
new { #class = "form-control subjects" })
The second parameter(source) is set empty since I want to load the source from an AJAX request; like below:
$.getJSON(url, function (response) {
$.each(response.Subjects, function (index, item) {
$('.subjects').append($('<option></option>').text(item.Text).val(item.ID));
});
// code to fill other dropdowns
});
Currently the html loads before the dropdowns are filled. So the values of all subject dropdowns are set to the default "Select Subject". Is there a way around this or is it the wrong approach?
Note: There are a number of dropdowns in this page. That's why I would prefer to load them an AJAX request and cache it instead of putting in viewModel and filling it for each request.
** EDIT **
In AJAX call, the action returns a json object containing dropdowns used across all pages. This action is decorated with [Output Cache] to avoid frequent trips to server. Changed the code in $.each to reflect this.
You can initially assign the value of the property to a javascript variable, and use that to set the value of the selected option in the ajax callback after the options have been appended.
// Store initial value
var selectedId = #Html.Raw(Json.Encode(Model.Subject.SubjectID))
var subjects = $('.subjects'); // cache it
$.getJSON(url, function (response) {
$.each(response, function (index, item) {
subjects.append($('<option></option>').text(item.Text).val(item.ID));
});
// Set selected option
subjects.val(selectedId);
});
However its not clear why you are making an ajax call, unless you are generating cascading dropdownlists which does not appear to be the case. What you doing is basically saying to the client - here is some data, but I forgot to send what you need, so waste some more time and resources establishing another connection to get the rest of the data. And you are not caching anything despite what you think.
If on the other hand your Subject property is actually a collection of objects (in which case, it should be Subjects - plural), then the correct approach using an EditorTemplate is explained in Option 1 of this answer.
Note also if Subject is a collection, then the var selectedId = .. code above would need to be modified to generate an array of the SubjectID values, for example
var selectedIds = #Html.Raw(Json.Encode(Model.Subject.Select(x => x.SubjectID)))
and then the each dropdownlist value will need to be set in a loop
$.each(subjects, function(index, item) {
$(this).val(selectedIds[index]);
});
If your JSON tells you what option they have selected you can simply do the following after you have populated your dropdown:
$('.form-control.subjects').get(0).selectedIndex = [SELECTED_INDEX];
Where [SELECTED_INDEX] is the index of the element you want to select inside the dropdown.

Save edited inline text from CKEditor 4 asp net

I am trying to implement CKEditor 4 into an ASP NET website that I am working on, but I cannot figure out how I would save the edited material from the inline editor I know how to do it with the the old version, but I just don't understand the process for this.
I have looked in the forums... There is not v4 forum.
I looked in for the documentation.... Couldn't find it.
I have a feeling that this is a simple task, but I just don't know how.
You can get your data with CKEDITOR.instances.editor1.getData(). Then you can send it via AJAX or store it as a value of some input field. To do this periodically, follow this method:
CKEDITOR.disableAutoInline = true;
var editor = CKEDITOR.inline( 'editable' );
var savedData, newData;
function saveEditorData() {
setTimeout( function() {
newData = editor.getData();
if ( newData !== savedData ) {
savedData = newData;
// Send it with jQuery Ajax
$.ajax({
url: 'yourUrl',
data: savedData
});
// Or store it anywhere...
// ...
// ...
}
saveEditorData();
}, 500 );
};
// Start observing the data.
saveEditorData();
You can also observe the submit event and update some (hidden) form field with your data.
Have fun!
Are you trying to get it with AJAX or send with a form? The value of for example the top right inline editor area with Lorem Ipsum can be gotten like in the older version with simply
CKEDITOR.instances.editor1.getData().
In the XHTML output example they have a simple form that seems to work and I believe that using an (static) inline editor is just the same.
If you transform elements into editors inline dynamically, I would try to bind to the submit event and before submitting loop through all CKEDITOR.instances, get their data into hidden from fields. As for the hidden field naming or identifying which hidden field corresponds to which dynamic editor you'll have to figure out yourself :)

How to bind events to element generated by ajax

I am using RenderPartial to generate CListView and all the contents generated properly and good pagination is working fine too. But when I added my custom JS to elements generated by the CListview it works fine for the the fist page content but when i use pagination and click to page 2 then the JS binding fails.
Is there any other way to bind custom event to elements generated in YII CListview I had tried using live, and on nothing work for me here is my js file.
I think I have to call my function on every ajax load in but how can I achieve in yii
This is the script I am using to update ratings on server with button click and this the element for which these forms and buttons are defined are generated by CListview in yii
$(document).ready(function(){
$('form[id^="rating_formup_"]').each(function() {
$(this).live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
});
You can also try CGridView.afterAjaxUpdate:
'afterAjaxUpdate' => 'js:applyEventHandlers'
The $.each method will loop only on existing elements, so the live binder will never see the ajax-generated content.
Why don't you try it like this:
$(document).ready(function(){
$('form[id^="rating_formup_"]').live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
This problem can be solved by two ways:
Use 'onclick' html definitions for every item that is going to receive that event, and when generating the element, pass the id of the $data to the js function. For example, inside the 'view' page:
echo CHtml::htmlButton('click me', array('onclick'=>'myFunction('.$data->id.')');
Bind event handlers to 'body' as the framework does. They'll survive after ajax updates:
$('body').on('click','#myUniqueId',funcion(){...});

Loading dynamic "chosen" select elements

I am using the jQuery plugin chosen (by Harvest). It is working fine on (document).ready, but I have a button that, when clicked, uses ajax to dynamically create more select objects that I want to use the "chosen" feature. However, only the original select elements have the "chosen" features, and the new (dynamically created) do not work. I am using jQuery.get to append the new elements. Here is a sample of the code:
jQuery(".select").chosen();//this one loads correctly
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
//response contains html with 2 more select elements with 'select' class
jQuery('#stages').append(response);
jQuery(".select").chosen();//this one doesn't seem to do anything :-(
});
});
I was thinking that I need a .live() function somewhere, but I haven't been able to figure that out yet. Any help is much appreciated!
Note - I am not trying to dynamically load new options, as specified in the documentation using trigger("liszt:updated");
Ensure that the response elements have the select class.
console.log( response ); // to verify
May also be a good idea to only apply the plugin to the new element(s).
jQuery(".select").chosen();
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
console.log( response ); // verify the response
var $response = $(response); // create the elements
$response.filter('.select').chosen(); // apply to top level elems
$response.find('.select').chosen(); // apply to nested elems
$response.appendTo('#stages');
});
});
Also, if /myurl is returning an entire HTML document, you may get unpredictable results.
after you code (fill the select) .write this
$(".select").trigger("chosen:updated");
I had a similar problem with Chosen. I was trying to dynamically add a new select after the user clicks on a link. I cloned the previous select and then added the clone, but Chosen options would not work. The solution was to strip the Chosen class and added elements, put the clone in the DOM and then run chosen again:
clonedSelect.find('select').removeClass('chzndone').css({'display':'block'}).removeAttr('id').next('div').remove();
mySelect.after(clonedSelect);
clonedSelect.find('select').chosen();
one way you can use chosen with ajax:
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
cache: false,
data: search
}).done(function(data){
$.each(data, function(){
$('<option />', {value: this.value, text: this.text}).appendTo(selectObj);
});
chosenObj.trigger('liszt:updated');
});
where selectObj is particular select object
But ...
Chosen is implemented very bad.
It has several visual bugs, like: select some option, then start searching new one, then remove selected and the keep typing - you will get 'Select some options' extended like 'Select some options search value'.
It doesn't support JQuery chaining.
If you will try to implement AJAX you will notice, that when you loose focus of chosen, entered text disappears, now when you will click again it will show some values.
You could try to remove those values, but it will be a hard time, because you cannot use 'blur' event, because it fires as well when selecting some values.
I suggest not using chosen at all, especially with AJAX.
1.- Download Livequery plugin and call it from your page.
2.- Release the Kraken: $(".select").livequery(function() { $(this).chosen({}); });
This is an example of Chosen dynamically loading new options form database using ajax every time Chosen is clicked.
$('.my_chonsen_active').chosen({
search_contains:true
});
$('.my_chonsen_active').on('chosen:showing_dropdown', function(evt, params){
id_tosend=$(this).attr("id").toString();
$.get("ajax/correspondance/file.php",function(data){
$('#'+id_tosend).empty();
$('#'+id_tosend).append(data);
$('#'+id_tosend).trigger("chosen:updated");
});
});

implement chanied filters/seach options in a datagrid using ajax

Let´s say I have some sort of datagrid and I want to add a couple chained filters like in this site:
http://www.yelp.com/search?find_desc=bar&ns=1&find_loc=Minneapolis%2C+MN
(sort by,distance,price etc).
Each time a user clciked in a filter link it will update the content of datagrid accordingly. But I would also need to update the links in other filters to take account of the changes. Ex: if i change the order field I need to add/update ?order_field=x in all the other filters links.
What you think is the best way to implement such scenario?
Should i create a function that, when a filter link is clicked, it update the query string params of all the other filters? Or use hidden fields to record the selected option in each filter?
I would like a reusable solution if possible.
Since the data is loading via AJAX, there shouldn't be any links to update - at least not if you mean anchor tags <a>. You don't even need to store the filters in a hidden field.
I would store all the filters as a JSON object. Depending on how your API is set up, you may have to convert the JSON object to something usable by your API or you may even be able to pass on the JSON object directly in the $.ajax request.
This sample code assumes you have a textbox with id="price" in the markup. I intentionally left convert_filters_to_parameters blank because you didnt provide any details as to your API. jQuery will in turn serialize those parameters into a GET or POST request before it sends them out.
var filters = {
distance:null,
price:null,
sortBy:'distance'
}
//this assumes you have a textbox with id="price"
$('#price').changed(function()
{
filters.price = $(this).val();
refresh_data();
});
function refresh_data()
{
var parameters = convert_filters_to_parameters(filters);
$.ajax('/my_api',
{
//i left out a lot of properties here for brevity
data: parameters,
success: function(response) { alert(response); }
});
}

Resources