am using HTML Editor (ajax toolkit) in my asp.net application.
Problem: my problem is when I want to assign or set the value to HTMLEditor on page load but it is not working(code below).
but with the same code I can retrieve or get the value successfully.
JavaScript:
<script type="text/javascript">
$(document).ready(function ()
{
document.getElementById("ContentPlaceHolder1_Editor1_ctl02").contentWindow.innerHTML = "Some value from db";
// not working :(
});
function getValue()
{
var content = document.getElementById("ContentPlaceHolder1_Editor1_ctl02_ctl00").contentWindow.document.body.innerHTML
// this working perfect.
}
function copyText()
{
document.getElementById("ContentPlaceHolder1_Editor1_ctl02").contentWindow.innerHTML = "Some Value from another div";
// working perfect.
}
</script>
My problem is I am not able to set the value in HTML Editor in document ready function. but the same way I can copy content of another div and I am able to set that text inside HTML Editor.
please give me suggestion how can I set the value in HTML Editor inside the document.ready event
Thanks,
It could be a timing issue because the html editor, when it loads, does have some javascript to run. You could try
window.setTimeout(document.getElementById("ContentPlaceHolder1_Editor1_ctl02").contentWindow.innerHTML = "Some value from db",0);
to place your code at the end of the stack.
Related
On our SharePoint 2013 page we have a button which runs an EXE
I want to generate a JS Alert when the button is clicked so that users know to click RUN
The buttons are being generated by a Content Search Web Part which is reading from a list with a Title and URL field.
For the EXE my url is this: file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe
I tried to embed the JavaScript inline using code such as: javascript:open('file:///S:/Web/EmailSignature_WPF/EmailSignature_WPF.exe') or more basically: JavaScript:alert('TEST');
But SharePoint is giving me an "Invalid URL" message when I try to embed JS in this manner.
I have instead now moved to a Script Editor Web Part and am trying to add the Alert to the OnClick event of my button but this is where I am stuck.
My Script Editor code:
<script style="javascript;">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick="javascript:alert('event has been triggered')";</script>
Here is an image of the IE Debug screen which is how I'm pulling the ID. This H2 element is wrapped in an HREF which is wrapped in two DIV tags which make up an LI
With the above snippet IE Debug is giving me this error message:
Unable to set property 'onclick' of undefined or null reference
I am hoping that this is as simple as misplaced quotations, or assigning the OnClick event to the wrong element, but I'm spinning my wheels. Any help appreciated and I'm happy to clarify
You should associate a function to the onclick event on img
<script type="text/javascript">
var img = document.getElementById('ctl00_ctl40_g_a225dbb9_1900_49f2_afe2_ab6f5bf77adf_csr4_pictureOnTop_line1');
img.onclick = function () {
alert('event has been triggered');
};
</script>
Say that your page is in the SitePages library and you use jQuery, you can add it to a folder called "js" in the SiteAssets folder, then go back to your Script Editor WP and do it like this:
<script src="../SiteAssets/js/jquery-3.6.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('input[id*="csr4_pictureOnTop_line1"]').on('click', function() {
alert('event has been triggered');
});
</script>
Basically, I'm working with static HTML that is written in stone. I cannot add an onclick to the dropdown menu, which is usually what I would do.
The following is what I have:
<script type="text/javascript">
function replicate() {
var tb1 = document.getElementById("ctl00_ContentPlaceHolder1_DropDownList_Country_17");
var tb2 = document.getElementById("ctl00_ContentPlaceHolder1_TextBox_State_19");
tb2.value = tb1.value;
}
</script>
Of course, this works fine for the actual "transfer" of data from the drop down to textbox, but it never gets executed. Usually I would execute the function "onclick" in the HTML, but I cannot do that. Is there another way to "listen" for a click on that dropdown?
Just register the handler:
document.getElementById("yourdropdownID").onchange = replicate;
can you use JQuery? Link to JQuery (like all javascrip files) and do the following in a script tag somewhere (or add to your current script tag.
<script>
$(document).ready(function(){
//Use the ID of the control here:
$("#ct100_ContentPlaceHolder1_DropDownList_Country_17").change(function(){
replicate();
});
});
<script>
I've built a simple CMS with multiple layers of jQuery.ajax(), like so:
function navto(destination, pageToEdit, insertInto) {
// use JQuery's ajax method to control main navigation
if (pageToEdit == "undefined") {
var request = $.ajax({
url: destination
});
} else {
var request = $.ajax({
type: "POST",
url: destination,
data: pageToEdit
});
}
request.done(function(msg) {
if (insertInto) { $(insertInto).html( msg ); }
else { $("#mana_content").html( msg ); }
//alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( textStatus + ". This page could not be found." );
});
}
For example, index.php uses <li class="child" onclick="navto('inc/edit_pages.php');">Edit Pages</li> to load edit_pages.php into <div id="content"></div>
edit_pages.php uses $(document).on("click", "a.editPage", function(e) { load_page_for_edit(e); return false; }); (where load_page_for_edit() gathers and readies the information to be sent to the navto() function) to send something like edit_page.php?t=template.php&c=contentID
edit_page.php uses those values to look up the info it needs in the corresponding databases and then outputs something like template.php&c=content into its own <div id="page_to_edit"></div>... again, with another navto().
A user can then click on $('.edit_text') elements to un-hide a div with a TinyMCE textarea (called $('#editor')) inside.
The content is captured by var content = $('.edit_text').html()
Here's the problem: when I try to load the content variable into the TinyMCE textarea -- $('#editor').html(content); -- the textarea does not receive it. I can immediately follow this up with alert($('#mana_editor').html());, which outputs the correct content, but with HTML characters made safe (eg, <p> becomes <p&rt;). However, the content does not load into TinyMCE.
I'm guessing that I have an .ajax scope issue? That perhaps jQuery is trying to $('#editor').html(content); to a non-existent #editor on the template.php (recall that the #editor is on edit_page.php)? Any good resources for figuring out multiple layers of .ajax?
Tid-bits, clues, and things I've tried:
All of my jQuery functions are in a functions.js file, except for the TinyMCE init, which is at the end of edit_page.php.
Only index.php links to functions.js
I'm using TinyMCE 3.5.6, jQuery plugin package and jQuery 1.7.2.
I've attempted TinyMCE's pseudo-selector as well ($('textarea:tinymce') instead of $('#editor')), which throws an error in Firebug: "Error: Syntax error, unrecognized expression: tinymce" in jq.min.js (line 4).
After a user makes their changes in TinyMCE, an update button will load the new content into the $('.edit_text') that was clicked. Instead of loading what I type in, it loads the "safe" HTML mentioned above -- as though TinyMCE was bypassed entirely.
If I don't use the whole CMS and start by manually typing `get_page.php?t=template&c=content' into FireFox it works fine.
If I don't load TinyMCE, the jQuery will load the content into the textarea
This guy might be on to something... seems similar, but I'm not sure what his head.js contains, how to implement head.ready();, or if his problem is the same as mine.
This is my first project using Ajax, so I have a lot to learn. Any insights/suggested reading/solutions would be greatly appreciated!
Here's the problem: when I try to load the content variable into the
TinyMCE textarea -- $('#editor').html(content); -- the textarea does
not receive it. I can immediately follow this up with
alert($('#mana_editor').html());, which outputs the correct content,
but with HTML characters made safe (eg, becomes <p&rt;).
However, the content does not load into TinyMCE.
You need to know that tinymce is not equal your textarea.
On initialization of an editor instance the former textarea gets hidden and tinymce creates a contenteditable iframe - the tinymce editor. The former textarea gets updated with the actual content of the editor from time to time (on special events).
So what i think what you want to achieve is to write your content into the editor. To do this addressing the textarea using jQuery won't work (as you found put yourself).
You need to employ the javascript tinymce API here:
tinymce.get('your_former_textarea_id_needs_to_be_here').setContent(content);
I wrote one script which gets an image url through JSONP, and then I needed to write that to browser, this is a status image which is onling.png, offline.png and so on
my script looks like this.
<div id='STATUSDIV'></div>
<script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script type="text/javascript">$(document).ready(function()
{
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
function(res)
{
document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
});
});
</script>
using this code, I am able to get an image inside div statusdiv, however I can not use same code block twice on single page as both will point to same div.
quick thing I can do is that I can ask end user who will copy this code multiple time on each page to change div id so that that image will load on differnt div.
But I wanted to have same code wherever copied just writes image inline. kind of createelement and write in that element. but thats not working. document.write does not work either as it replaces everything.
Is there a way that when this code block called, Instead of writing innerhtml, code creates a dynamic div right there on the page and writes image in that. and this image writing and creating div happens where script block is called. so that If same script is called in header and footer, status image will appear on both header and footer.
The cleanest way I know of is to create a function for your code that should get included very early in the page so it's available everywhere:
function insertStatusHere() {
var thisId = "status" + insertStatusHere.myDivCntr++;
document.write('<div class="statusContainer" id="' + thisId + '"></div>');
$(document).ready(function() {
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(), function(res) {
document.getElementById(thisId).innerHTML = ("<img src='"+res.img+"' />");
});
});
}
insertStatusHere.myDivCntr = 0;
Then, any place in the page where someone wants a status image, they can put this inline script:
<script type="text/javascript">
insertStatusHere();
</script>
This dynamically inserts a div with a unique div ID at the place that the function call is made and it keeps track of each ID that is used in the closure.
I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.