Display tinymce textarea dynamically - javascript

I have a drop down list that when a selection is made will insert a bunch of elements within a form to the DOM using ajax, within this form I have textareas that I wish to be TinyMCE textareas.
I have this inside of my HTML head:
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
This is the ajax function that I use to add a bunch of elements, this is working how I need it to.
function getSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
}
});
//loadTinyMCEEditor();
};
I have other textareas on my page that are not inserted by ajax and they display as WYSIWYG editors no problem, the issue is when I am adding in new elements.
I have checked several other questions trying to find an "answer" but nothing is working.
I tried to make a function called loadTinyMCEEditor() that I was calling within my getSecFacility() function after my ajax call. Within this function I was trying to reinitialize tinyMCE for these newly added textareas.
loadTinyMCEEditor() looks like this:
function loadTinyMCEEditor() {
tinyMCE.init({
selector: "textarea"
});
tinyMCE.execCommand('mceAddControl', false, 'test'); //test is the class name I gave this textarea
//tinyMCE.execCommand('mceAddControl', true, 'test'); //tried setting the bool to true..even tried without these lines
}
No matter what I try I cannot seem to get it to work with newly inserted textareas, How can I get these textareas to be TinyMCE textareas?
EDIT
I can now view the editor to my newly added textareas after I make a selection from my drop down list. However this only works once, if I make a second selection the new textareas only display as plain textareas. Here is what I changed in my ajax function:
function getFacSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
loadTinyMCEEditor();
}
});
};
function loadTinyMCEEditor() {
tinymce.init({
selector: "textarea"
});
}
So after I make a selection this ajax function will run and display new textareas + other form information and I re-initialize the tinymce editors but for some reason this is only working once.
What should I change/do so that I can make multiple selection from my drop down list so that each time the new textareas will display as tinymce textareas?

You need to call tinyMCE.activeEditor.setContent with your incoming ajax-content. In your callback try:
tinyMCE.activeEditor.setContent(data);
Greetings

If you want to convert #selected_fac_section to a tinymce editor, you should call the init function of tinymce in your success function. Ajax calls are async unless you define otherwise. So, if you try to initialize the textarea outside of the ajax call, there still won't be a textarea to decorate with tinymce because the ajax call hasn't been finished yet. Use the id value for the selector this time and you should be good to go.
I am writing this from my phone so writing code here is a pain. Sorry for that. Just wanted to help you out quickly after seing you comment on my another answer. Will check this thread first thing in the morning to make sure if you need more help.

Related

Select2 is not working with elements added via Ajax

I am trying to add a new <select class="js-select-search"> element on the page through AJAX, but it seems that a standard call in that way doesn't work:
$('.js-select-search').select2();
I understand that it's a new element in the DOM, but I don't get how to make it work.
Select2 is a function. It runs once, and then never again. You can run it again however in the 'success' part of your ajax call.
$.ajax({
success: function () {
$('.js-select-search').select2();
}
})

Making jQuery function work with ajax call

I am trying to achieve something when i click the button. The button is loaded from the server using an AJAX call. However, nothing happens when the button is clicked. Here is my code:
(This ajax call is in JS Fiddle -- only for testing purposes)
JS Fiddle
Code:
<div id="target"></div>
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target'
}).send();
$("button").click(function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
Since the button does not yet exist you can use jQuery.on to delegate an event handler.
$("body").on('click', 'button', function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
Also your fiddle does not work since you are using both jQuery and MooTools but only loading MooTools.
Added after seeing authors page:
The var value = $(this).siblings(".title").text(); selector will not work. I would recommend adding an event class (as in calendar event) to the wrapper and using:
var value = $(this).parents(".event").find(".title").text();
If you are adding elements to the DOM via AJAX (or any other method) and you want listeners to remain bound to them, then you need to attach those listeners to elements in the document that don't change - like $(document).
e.g.
$(document).on('click','button',function(e) {
//your code here
});
The problem with your code is that you're getting all the buttons by doing $("button") and then attaching click listeners to them. The problem is that when you're doing this, your button hasn't been attached to the document and, therefore, will not have a click listener attached to it.
If button doesn't exist on page load. You can;t use $("button") to address it. You have to surround it by something else(div for example) and do it like this:
$('div').on('click','button', function(){...})
There are 2 things you need to consider.
ONE - jQuery that is included with mootools.
I was surprised that $ function in mootools version that you are using gave me a very BASIC jQuery function. I tried higher versions of mootools and still the same happened. I am sure it is not jQuery at all and mootools is just using $ variable for their purpose. [Optional: So, you may also consider defining jQuery as a different variable in your script.]
So, I added a link to latest jQuery in External Resources on jsfiddle and then it worked. Do not forget to expand External Resources on left on jsfiddle. But, if mootools is using $ for its own purpose, then jQuery will surely overwrite it. Please consider using jQuery as a different variable than $.
TWO - Use the onSuccess function of AJAX request.
You call the AJAX request and so you have to wait for some time for browser to load it which depends on user's internet connection. So, this is why we use onError and onSuccess events. Write the button function in onSuccess because button does not exist on document until AJAX is loaded.
Please check this code and it works.
http://jsfiddle.net/U7ewu/
Code:
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target',
onSuccess: function() {
$("button").click(function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});
}
}).send();
EDIT:
Please use $.noConflict(); so that mootools and jquery do not conflict each other on $ variable. $ is already being used by mootols, so please use the word jQuery instead.
Please check this jsfiddle.
http://jsfiddle.net/wkMep/
Code:
$.noConflict();
new Request.HTML({
url: '/echo/html/',
data: {
html: "<div id='0001'>"+"<h5 class='title'>Hello World</h5>"+"<h4 class='date'>2014-07-19</h4>"+"<button> Add to Calendar </button>"+"</div>",
delay: 0
},
method: 'post',
update: 'target',
onSuccess: function() {
jQuery("button").click(function(){
var value = jQuery(this).siblings(".title").text();
value += jQuery(this).siblings(".date").text();
alert(value);
});
}
}).send();
try this
$("button").on("click",function(){
var value = $(this).siblings(".title").text();
value += $(this).siblings(".date").text();
alert(value);
});

jquery select2 after ajax not working anymore

I have a simple select2 control on my site placed in a div. When the site loads, everything works fine. However, if the html content of the div "simpleDiv", where the Select2 is placed, is loaded with Ajax, the Select2 is not showing the results anymore when triggered.
That means, in this case the Select2 data is got from the Server, but never shown in the Select2.
And this all happens just when the "simpleDiv" html content is loaded with Ajax. Otherwise, everything works fine.
Can anyone help, please?
<div id='simpleDiv'>
<input type="hidden" id="MedikamentID" name="MedikamentID" class="fixed-width4" />
</div>
<script>
$('#MedikamentID').select2({
placeholder: "[Medikament]",
allowClear: true,
minimumInputLength: 2,
ajax: {
url: "/Medikament/List",
dataType: 'json',
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
</script>
Whenever you change things using .html() or .innerHTML, essentially, the DOM gets reconstructed and all the javascript events and properties attached to them is lost. But the fix is simple. Just call Select 2 again after you finished inserting the new HTML. So something like:
$.ajax("example.php").done(function(data){
$("#simpleDiv").html(data)
$("#MedikamentID").select2(...) //rebuild select2
})
I attached a jsfiddle to illustrate this:
http://jsfiddle.net/HT3rP/1/
If I got your question correct, you may be having a similar problem related to this stackoverflow problem
You could try something like this
$(document).on("ready", "#MedikamentID", function () {
$(this).select2({
// options go here
});
});

JS function doesn't work when AJAX request is done (Maybe a $(this) problem)

My site has a form which insert records in a database using ajax, at the same time, it "refreshes" a table also using AJAX in the same page showing this new record.
So I have the JS code
// New Record Div
$('button[type=submit]').click(function() {
// Read all the form content
var creditor = $('#selCreditor').val();
var reason = $('#txtReason').val();
var value = $('#txtValue').val();
var debtor = $('#selDebtor').val();
$.ajax({
type: 'POST',
url: 'index/insert/creditor/'+creditor+'/reason/'+reason+'/value/'+value+'/debtor/'+debtor,
success: function() {
$('#status').slideDown();
$('#latestRecords').fadeOut();
$.ajax({
type: 'POST',
url: 'index/latest',
success: function(html) {
$('#latestRecords').fadeIn();
$('#latestRecords').html(html);
}
});
}
});
return false;
});
Basically, it inserts a new record in the database, then on success, it requests a page which contains only the table and populate the div with the returned data. It's sort of a refresh when the data is submitted. Everything is done using AJAX.
I've uploaded the situation image for a better understanding. image
The Problem
Everything goes fine until you try to delete a "refreshed" table row. Without the AJAX (only press F5) I can delete any row I want through the delete button, but when I insert a row and the try to delete any row in the table won't do. This is the Delete button code
// TR Fading when deleted
$('.delete').click(function() {
$.ajax({
type: 'POST',
url: 'history/delete/id/'+$(this).attr('id')
});
$(this).closest('tr').fadeOut('slow', function() { $(this).remove(); });
$('#latest')
return false;
});
I suspect that the problem is $(this) which not refers to the delete button element once the table is refreshed, but I don't know how to fix it.
If the entire table is being reloaded then .click() wont work as it will have lost the elements it was applied to. Try using .live() instead.
e.g.
$('.delete').live('click',function(){...});
Also assign $(this) to a variable and use the variable instead, it can help make the code a bit clearer I think. e.g. var $deleteButton = $(this);
take a look at jquerys live, i think this is what you're looking for.
In addition to Nalums anwser, Who stated that you can use .live() — which will work even if you add dynamic elements through jQuery — you should instead use for most occasions the newer .delegate() (version added: 1.4.2)
Could be used in this fashion:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
Or check out api.jquery.com/delegate/ for more information.

Automatically initialize rich text editor on top of all textarea's, including ones that are loaded via ajax

I'm developing an ajax heavy web app, and would like to have textarea's (with class="ui-richtext") automatically initialize TinyMCE.
This is easy for textarea's that are loaded normally, but how about for content that is loaded AFTER the fact using ajax?
I was thinking something along these lines: (i'm using jquery)
$("textarea.ui-richtext").live("ajaxComplete", function()
{
$(this).tinymce({...});
});
Unfortunately this doesn't seem to work. Any ideas?
This is my first post, let me know if I need to add more info
Live is limited to a small number of events.
You can do something like this though:
$.ajax({
url: 'url/here',
success: function(data){
var $data = $(data).("textarea.ui-richtext").tinymce();
$('#mydiv').append($data);
}
});

Categories