Get input field value from dialog box in TinyMCE - javascript

all.
I'm having a hard time figuring this out, it's the second time I need to do something with tinyMCE but this time I just can't find the answer.
Here's what I want to do: I have added a button on my editor that opens a new popup with a single text input field and a button. I want to click the button and grab the value I set in my input field, then use that value to modify what I have in my editor.
Here's what I have so far - only relevant code:
init : function( ed, url ) {
ed.addCommand( 'mceTooltip', function() {
ed.windowManager.open({
file: 'imageurl.html',
width: 480,
height: 180,
inline: 1,
title: 'Please enter an image URL'
}, {});
});
}
This is what imageurl.html has:
<input type="text" id="image-url" />
<input type="button" id="submit-image-url" value="Ok" />
So, what I need to do is get whatever "image-url" text input has whenever I click the OK button, and use that text inside my editor. I know I can use ed.selection.setContent( fieldValue ) and it will replace my selected text with the image-url value, I just don't know how to get the image-url value.
The most detailed info I was able to find was http://www.tinymce.com/wiki.php/How-to_implement_a_custom_file_browser but I can't make it work for my needs.
Anybody who can help me out with this? I'm sure it should be simple for somebody with more experience on this.
Thank you all for your attention.
Updated imageurl.html **
<script>
document.getElementById( 'submit-image-url' ).onclick = function(){
var imageUrl = document.getElementById( 'image-url' ).value;
window.parent.tinyMCE.activeEditor.execCommand( 'mceInsertContent', 0, imageUrl );
window.parent.tinyMCEPopup.close(); // this line gets me this error: "Uncaught TypeError: Cannot read property 'windowManager' of undefined "
};
</script>

Ok, this shouldn't be that difficult.
issue this in a script-tag on bottom of your imageurl.html or use a document ready javascript function. The following will add an onclick handler to your button which will get the image_url and write this to the tinymces selection.
$('#submit-image-url').bind('click', function(){
var image_url = $('#image-url').val();
// in case you are using a real popup window
window.opener.tinymce.activeEditor.selection.setContent(image_url);
// in case you use a modal dialog
tinymce.activeEditor.selection.setContent(image_url);
});

You have opened up a window so you are currently in IFrame having imageurl.html ok..
what you have to do is
on a parent page create one variable of global type like
var image_url = "";
now on imageurl page create a script on body part like this
<body>
<script>
$("#button").click(function(){
window.parent.image_url = $('image-url').val();
});
</script>
</body>
make sure you have jquery on imgurl. or otherwise use addeventlistener or attachevent
method
logic is get parent window's element from the iframe and save it from iframe.

Ok, I found the problem. I had to include tiny_mce_popup.js inside imageurl.html, that's why the tinyMCEPopup.close() didn't work:
<script type="text/javascript" src="js/tinymce/tiny_mce_popup.js"></script>
<script>
document.getElementById( 'submit-image-url' ).onclick = function(){
var imageUrl = document.getElementById( 'image-url' ).value;
tinyMCEPopup.execCommand( 'mceInsertContent', 0, imageUrl );
tinyMCEPopup.close();
};
</script>
I wrongly assumed it was being loaded because I was able to see the popup.
Originally I didn't want to modify imageurl.html, but it looks like that's just the way it has to be done...
Anyway, I already knew how I could address some of these tasks from inside imageurl.html file, and I had already seen tinyMCEPopup had a close() method, but to keep it fair, I'll accept the answer from the person who I felt was more active in trying to help me out.
Thanks everyone.

Final code will like this.working ...
imageurl.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="tiny_mce_popup.js"></script>
</head>
<body>
<input type="text" id="image-url" />
<input type="button" id="submit-image-url" value="Ok" />
<script>
document.getElementById( 'submit-image-url' ).onclick = function(){
var imageUrl = document.getElementById( 'image-url' ).value;
tinyMCEPopup.execCommand( 'mceInsertContent', 0, imageUrl );
tinyMCEPopup.close();
};
</script>
</body>
</html>

Related

Changing text inside an iframe with JS

I have an HTML page which loads some content in an iframe with the help of remote JS. I want to replace the text "premium content" with something else.
What I am trying is:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://gaand.comli.com/no.js"></script>
<img src="psss" onerror="myFunction()"></img>
<script>
function myFunction() {
var x = document.getElementById("overlay_iframe");
var y = x.contentDocument;
y.document.body.innerHTML = y.document.body.innerHTML.replace('premium',
'newtext');
}
</script>
</body>
</html>
Is there any way to change it as soon as the page is loaded completely?
You can use jquery to have event when page loads, and then replace html content.
$( document ).ready(function() {
$( "#overlay_iframe" ).html( $( "#overlay_iframe" ).html().replace("premium","newtext"));
});
Unless the iFrame is on your server you cannot change it. I would suggest using PHP
file_get_contents()
and replacing it within the string.
You can try using the jQuery .contents() to return an object of the iframes contents and than manipulate that. jQuery .contents()
Edit, updated
Try
$.getScript("http://gaand.comli.com/no.js")
.done(function(script) {
s = setInterval(function() {
$("iframe").contents()
.find("body").text(function(_, o) {
return o.replace("premium", "newText");
}) && clearInterval(s);
}, 10);
});
jsfiddle http://jsfiddle.net/guest271314/whjqqtco/

Working with getElementById( x ).onclick = someFunction

I thought for long how to define the question but i couldn't, i need to explain the code.
I want to make a simple organizer in JavaScript. You enter the task and click on the button "add to the list" and a script makes a checkbox with paragraph that contains the task's text. The second part is the disabling the checkbox, and striking through that tasks text when you click on it. I tried to do that by giving every checkbox i create a function (destroyIt() that gets element by id and than disables it, but it works only for the last checkbox added to the page. I am looking at this code for long time and i can't see what is wrong. Please help. Here is my code:
<html>
<head>
<style id="stil">
.over{
text-decoration:line-through;
}
</style>
<script type="text/javascript">
var numberOfTasks=1;
function insertNew(){
tekst = document.getElementById("zadatak").value;
if(tekst.length>0){
var idEl= "check"+numberOfTasks;
document.getElementById("ispis").innerHTML+="<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>";
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
numberOfTasks++;
}
}
function destroyIt(idEl){
document.getElementById(idEl).disabled=true;
document.getElementById("stil").innerHTML+= "."+idEl+"{text-decoration:line-through;}";
alert(idEl+"{text-decoration:line-through;}");
}
</script>
</head>
<body>
Tasks for: <span id="date"> </span>
<script>
var date= new Date();
document.getElementById("date").innerHTML= ""+ date.getDay() +"." +date.getMonth() +"." +date.getFullYear();
</script>
<br/> <br/>
New task: <input type="text" id="zadatak"> <button onclick="insertNew()"> add to the list </button>
<button onclick="provera()">Provera</button>
<p id="ispis"> </p>
</body>
The problem is that when you do .innerHTML += "...", it destroys the existing nodes and their event handlers, and replaces them with new, clean nodes. For this and other reasons, you should almost never use += after .innerHTML.
A better way to insert new content from HTML markup is to use .insertAdjacentHTML() instead. The first argument describes the position relative to the element on which it was invoked, and the second argument is the new content.
So your code with .insertAdjacentHTML() would look like this:
function insertNew(){
tekst = document.getElementById("zadatak").value;
if(tekst.length>0){
var idEl= "check"+numberOfTasks;
document.getElementById("ispis")
.insertAdjacentHTML("beforeEnd", "<input type='checkbox' id='check"+numberOfTasks+"'> "+"<span class='"+idEl+"'>"+tekst+"</span> <br/>");
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
numberOfTasks++;
}
}
Furthermore, you can modify the destroyIt function to operate on its this value, which will give you the input element that has the handler. You can then use its .id to get the class of the span, or you can just traverse to the next element.
Also, you shouldn't modify the style sheet to hide the element. Just add a class or a direct style property.
So in the above function, this:
document.getElementById(idEl).onclick= function(){ destroyIt(idEl); };
becomes this:
document.getElementById(idEl).onclick= destroyIt;
And then the destroyIt function becomes this:
function destroyIt(){
var span = this.nextElementSibling;
this.disabled=true;
span.style.textDecoration = "line-through";
}
The .nextElementSibling will need to be patched in IE8, but this is just for simple demonstration.

how to fix the closure bug in my jQuery code

the page always alert "btn2" ,whenever I click btn1 or btn2. it's seem the problem caused the "click" closures.but I don't know how to fixed it.
thanks in advance.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>untitled</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
(function(){
$.fn.test = function(){
F.init.apply(this,arguments)
};
var F ={
that:null,
init:function(){
F.that = this;
$(F.that).click(function(e) {
F.method();
});
},
method:function(){
var text =$(F.that).html();
alert(text);
}
}
})();
$(function(){
$("#btn1").test(); //alert btn2---bug
$("#btn2").test(); //alert btn2
});
</script>
</head>
<body>
<button id="btn1">btn1</button>
<button id="btn2">btn2</button>
</body>
</html>
You have referred to your object class F by that name from within the class.
Your line F.that = this is effectively therefore creating what would in other OO languages be considered a "static member" of the class, so both #btn2 and #btn1 ended up sharing the same that member.
Furthermore, your click handler is trying to call F.method() - in effect also a static method call.
You'll need to create a new object of type F each time you wish to wrap it around an element. Only then will you get a separate this for each element.
I suggest using an off-the-shelf jQuery plugin model such as http://jqueryboilerplate.com/ instead of trying to invent your own. See this extract from that code:
$.fn[ pluginName ] = function ( options ) {
return this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
};
Note how it uses new Plugin to create the plugin instance, and then stores it on the element using $.data, but only the first time the plugin is invoked against each element.
1)F is a static Object
2)So F.that is also static
3)so
F.that = this
line will set 'this' to F.that.
4)first time you call
$("#btn1").test();
then F.that will be equal to $("#btn1");//this will be equal to $("#btn1")
5)Next time you call
$("#btn2").test();
then F.that will be equal to $("#btn2");//this will be equal to $("#btn2")
6) So finally to F.that you are setting $("#btn2")
7)hence the $(F.that).html(); is essentially $($("#btn2").html()) which is further same as $("#btn2").html()
8)Hence alert is showing "btn2"

how to get tinyMCE editable for a cloned textarea by cloneNode(true) function

When I try to clone a textarea by using cloneNote(true), the cloned textarea is not editable. Does anyone know how to resolve the problem? The sample codes show as following:
<html>
<head>
<script type="text/javascript" src="/javascripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode : "textareas",
});
</script>
<script type="text/javascript">
testclonenode = {
addAbove : function (element) {
var rowEl = element.parentNode.parentNode.parentNode;
var rowElClone = rowEl.cloneNode(true);
rowEl.parentNode.insertBefore(rowElClone, rowEl);
return false;
}
};
</script>
</head>
<body>
<table>
<tr><td>
<textarea name="content" style="width:100%">this is a test </textarea>
<p> <button onclick='return testclonenode.addAbove.call(testclonenode, this);'> Add above </button>
</td></tr>
</table>
</body></html>
It does not work that way. Also, it is impossible to move a tinymce editor using dom manipulation.
The tinymce wiki states the following:
mceAddControl
Converts the specified textarea or div
into an editor instance having the
specified ID.
Example:
tinyMCE.execCommand('mceAddControl',false,'mydiv');
So when you clone a textarea there is another problem: You will have the same id twice which will result in errors accessing the right tinymce instance.
I got this to work by using an ID which is incremented each time my clone function is triggered, so
var insertslideID = 0;
function slideclone() {
$('<div class="slides"><textarea name="newslide['+insertslideID+'][slide_desc]" id="mydiv'+insertslideID+'"></textarea></div>').insertAfter('div.slides:last');
tinyMCE.execCommand('mceAddControl',false,'mydiv'+insertslideID);
insertslideID++;
}
$('input[name=addaslidebtn]').click(slideclone);
Seems to work.
A wee bit tidier, I just use a number for my id - copy1 is the name of my button - I add the new element to the end of my container.
var count = 0;
$("#copy1").click(function(){
var newId = count;
$( "#first" ).clone().appendTo( "#container" ).prop({ id: newId, });
tinyMCE.execCommand('mceAddControl',false,newId);
count++;
});
I ran into a similar problem, except my element IDs (not just textareas) could be anything, and the same ID was always appearing twice. What I did is supposed to be horribly inefficient but there was no noticeable performance loss with dozens of elements on the page.
Basically I removed the TinyMCE ID first (uses jQuery):
$(new_element).find('.mce-content-body').each(function () {
$(this).removeAttr('id');
});
Then I reinitialized TinyMCE for all relevant elements.

Get a Div Value in JQuery

I have a page containing the following div element:
<div id="myDiv" class="myDivClass" style="">Some Value</div>
How would I retrieve the value ("Some Value") either through JQuery or through standard JS? I tried:
var mb = document.getElementById("myDiv");
But the debugger console shows "mb is null". Just wondering how to retrieve this value.
---- UPDATE ----
When I try the suggestion I get: $ is not a function
This is part of a JQuery event handler where I am trying to read the value when I click a button. The handler function is working but it can't interpret the jQuery value it seems:
jQuery('#gregsButton').click(function() {
var mb = $('#myDiv').text();
alert("Value of div is: " + mb.value);
});
$('#myDiv').text()
Although you'd be better off doing something like:
var txt = $('#myDiv p').text();
alert(txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>
Make sure you're linking to your jQuery file too :)
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
if you div looks like this:
<div id="someId">Some Value</div>
you could retrieve it with jquery like this:
$('#someId').text()
your div looks like this:
<div id="someId">Some Value</div>
With jquery:
<script type="text/javascript">
$(function(){
var text = $('#someId').html();
//or
var text = $('#someId').text();
};
</script>
You could use
jQuery('#gregsButton').click(function() {
var mb = jQuery('#myDiv').text();
alert("Value of div is: " + mb);
});
Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.
You could also use innerhtml to get the value within the tag....
You can do get id value by using
test_alert = $('#myDiv').val();
alert(test_alert);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>

Categories