CKEditor Insert HTML - javascript

I have a data from database.
In my js file, I would like to change my CKEditor text editor's value.
My value is raw html.
I want this raw value to be written on an empty CKEditor text editor.
I tried these but got an undefined function error all the time :
CKEDITOR.instances.myEditorID.insertHtml( '<p>This is a new paragraph.</p>' );
CKEDITOR.instances.myEditorID.setData( '<p>This is the editor data.</p>' );
I tried this too but still undefined function error :
CKEDITOR.instances.YOUREDITORID.updateElement();
alert( document.getElementById( 'YOUREDITORID' ).value );
Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still doesn't work for me.
Thanks in advance.
---Update---
This is the html of my ckeditor text editor :
<textarea id="myEditorID" name="myEditor"></textarea>
<script type="text/javascript">
$(function () {
var myEditor = $('#myEditorID');
myEditor.ckeditor({
height: 200,
extraPlugins: 'charcount',
maxLength: 2000,
toolbar: 'TinyBare',
toolbar_TinyBare: [
['Bold','Italic','Underline'],
['Undo','Redo'],['Cut','Copy','Paste'],
['NumberedList','BulletedList','Table'],['CharCount']
]
}).ckeditor().editor.on('key', function(obj) {
if (obj.data.keyCode === 8 || obj.data.keyCode === 46) {
return true;
}
if (myEditor.ckeditor().editor.document.getBody().getText().length >= 2000) {
alert('You have reached the maximum char length');
return false;
}
});
});
</script>

Instead of myEditorID i tried 'editor', 'editor1', 'editor2' but still
doesn't work for me.
You need to look at the HTML of your page and see what the ID field is for your editor. It will be something like this
<textarea id="my_editor"></textarea>
That id attribute is what needs to go in here
CKEDITOR.instances.my_editor.insertHtml('<p>This is a new paragraph.</p>');

If you have a CKeditor like
<textarea id="user_body"></textarea>
To insert data, Please use the following line of Code
CKEDITOR.instances["user_body"].insertHtml('');
Hope it will work for you. Thanks

In your HTML
<textarea name="contenteditor" id="contenteditor" style="margin:0px 10px;">
</textarea>
In your JavaScript (JQuery)
$(function(){
CKEDITOR.replace('contenteditor');
//Your data
var yourData = '<p>This is a new paragraph.</p>';
//insert your data in the editor
$("#contenteditor").val(yourData);
})

Related

How to check if string contains url anywhere in string using javascript and convert it to anchor tag

I have a textarea in which I am getting user's input data. But I need to know if there is any URL in textarea and convert it to anchor tag. For example:
Textarea Data:
Hi I'm Abdul. My Website is https://website.com
After Anchor Tag:
Hi I'm Abdul. My Website is https://website.com
Currently my code is:
var status = $('#status').val();
var urlCheck = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if(urlCheck.test(status)) {
alert("url inside");
console.log(urlCheck.exec(status)[0]);
}
This is my current code but I don't know how to replace url with anchor tag in that string.
I am not sure if i understand you correctly, but do you want to have it changed live or after the form was sent? If the latter, i would try something like this:
var urlCheck = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if(urlCheck.test(status)) {
alert("url inside");
console.log(urlCheck.exec(status)[0]);
// Here my possible solution (not tried out)
$('#status').val('<a href="http://'+urlCheck.exec(status)[0]+"' target='_blank'>the link</a>");
}
But this would also mean that you could/must check with a RegEX if the user entered http or not.
var status = $('#status').text();
var urlCheck = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if(urlCheck.test(status)) {
alert("It has an URL!");
console.log(urlCheck.exec(status)[0]);
}
document.getElementById("status").innerHTML = status.replace(urlCheck.exec(status)[0],"<a href='"+urlCheck.exec(status)[0]+"'>"+urlCheck.exec(status)[0]+"</a>");
<div id="status">Hi I'm Abdul. My Website is https://website.com</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
We can use the html.replace() to replace the url inside the tags we wanted.
You have to use the JS replace() function.
I set the following example with an input textarea and an output textarea for let you see the difference.
function addUrl() {
var status = $('#status').val();
var urlCheck = /(([a-zA-Z0-9]+:\/\/)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\.[A-Za-z]{2,4})(:[0-9]+)?(\/.*)?)/;
$('#output').val(status.replace(urlCheck, '$1'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="status">Input</label>
<textarea id="status" onChange="addUrl()"></textarea>
<br/>
<label for="output">Output</label>
<textarea id="output"></textarea>
use linkifyHtml or linkifyString : Linkify String Interface. Use linkify-string to replace links in plain-text strings with anchor tags.

ajax-generated form with php-inserted values via javascript function--- elements don't exist when I check them by id?

I would like to prepopulate the fields of a form I display in a modal view via jquery after getting the form HTML with an ajax query. I am prepopulating the fields via a document.getElementById call to set the value in a javascript function, with the values in the javascript function generated with php code.
The problem is that the fields I want to populate with values don't seem to exist even after the callback function from the AJAX call has imported the form code. When I check if the elements exist in my function to set the values of those elements, I see a null return, so the elements are not there. What's going on?
I can see that in the html source code, the php has put the correct form values in. However, I do not see the textarea value/innerHTML displayed. Rather the textarea is blank. Is there something tricky about text areas?
Thank you for any suggestions.
Here is the Jquery/javascript:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script>
$(function() {
var dialog, form,
dialog = $( "#dialog-form2" ).dialog({
autoOpen: false,
height: 550,
width: 400,
modal: true,
});
$( "#create-user2" ).button().on( "click", function() {
showform();
dialog.dialog( "open" );
});
});
</script>
<div id="dialog-form2" style="background-color: white; border: 4px solid #f1f1f1; padding: 20px;" >
</div>
<div id="dialog-form2" style="background-color: white; border: 4px solid #f1f1f1; padding: 20px;" ></div>
<script>
function showform()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("dialog-form2").innerHTML=xmlhttp.responseText;
updateform();
}
}
xmlhttp.open("GET", "newinstructions.html");
xmlhttp.send();
}
function updateform()
{
document.getElementById('f1').value = '<?php echo $included;?>';
document.getElementById('f2').value = '<?php echo $id_bus;?>';
document.getElementById('f3').value = '<?php echo $deals_id;?>';
document.getElementById('f4').value = '<?php echo $_SESSION['token'];?>';
document.getElementById('details').innerHTML = '<?php echo $instructions1;?>';
document.getElementById('details').value = '<?php echo $instructions1;?>';
}
</script>
Here is the form:
<form method = "post" action = "changeinstructions.php">
<textarea rows = "8" cols = "60" name = "details" id = "details" ></textarea>
<input type = "hidden" name = "included" '/>
<input type = "hidden" name = "id" />
<input type = "hidden" name = "deals_id"/>
<input type = "hidden" name = "token" />
<br>
<input type="submit" tabindex="-1" >
</form>
And finally I include this in a php file as include_once('jquery.php') and I have verified that all the php variables exist and have values just before this include statement. Here is what the html source code looks like as resulting for the javscript function setting values:
function updateform()
{
document.getElementById('f1').value = '1';
document.getElementById('f2').value = '59';
document.getElementById('f3').value = '226';
document.getElementById('f4').value = '7a7dd52df381577c7b8e2518aa9b2808';
document.getElementById('details').innerHTML = ' dumb instructions';
document.getElementById('details').value = ' dumb instructions';
}
So the function updateform() has the right values, and this function should only be called after the form itself has been created. Yet no values appear on the form, and no values appear in the POST array after I submit the form. What gives? Thanks for any advice.
you want to populate the inserted values into a new popup modal or dialog ??
please explain more what you are trying do,
if iam correct , you dont need to re-include jquery code you can do this in a callback function instead
////edit
you can use .val() to set or get textarea
//edit
you are using a get in your ajax , while your form is using POST
i wounder if you are using $_GET or $_POST in your php , this is confusing
//
the solution as follows :
//
you need to select the textarea not by its id alone,
you need to select the top parent first ,
then second top parent
example :
if you open you console you will find it something like this (after the popup appear)
<div id="popup top div"><div id="another parent"><form><textarea id="details"> ,
all you need to do is something like
var target_textarea =$("#topid #secoundtopid #details") then use the target_textarea.val();
Basically, your ajax needs attention.
When the AJAX routine is run (and I recommend using jQuery, as it's simpler and much less typing -- see posts at bottom) the server sends the response back in the variable responseText. You cannot use <?php echo etc etc; ?> to get the returned data -- it isn't there. It's in the responseText variable.
Also, that variable is local to (and only available in) the xmlhttp.onreadystatechange function.
Simple AJAX:
AJAX request callback using jQuery
After you render the new page, the javascript needs to call the function updateform() to populate the html DOM.
window.onload=updateform;
You can also call it in the <body> element <body onload="updateform()">

JavaScript Error because of rendered velocity line-break

I use JavaScript-code in a velocity-template and it's not working!
I read content with this template and want to set this to a js-variable, but there are line-breaks in the content and I get the following error:
SyntaxError: unterminated string literal
In the rendered code there you see the error:
var exampleText = 'This is the first line
and this is the second line.';
In the original code it is written this way:
var exampleText = '$question.answer.data';
var regularPanels = new A.Panel( {
bodyContent: exampleText,
collapsible: true,
collapsed: true,
headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');
});
Is there a possibility to ignore the linebreak for the js-compilation, but still show it on the complete rendered page?
Okay, I solved it with the help of the EscapeTool by Velocity.
Combined with the answer from emiliocai it's the following code which works fine:
<div id="example-text" style="display:none;">
<p>$escapeTool.java($question.answer.data).replace("\n","<br />")</p>
</div>
<script type="text/javascript" charset="utf-8">
AUI().ready('aui-panel', function(A) {
var exampleText = document.getElementById('example-text').innerHTML;
var regularPanels = new A.Panel( {
bodyContent: exampleText,
collapsible: true,
collapsed: true,
headerContent: '$question.data' } ) .render('#regularPanels$counter$reserved-article-id.data$randomNamespace');
});
</script>
It might be, that it would work without the hidden <div>-Tag, but I haven't tested it yet.
So also possible would be:
var exampleText = '$escapeTool.java($question.answer.data).replace("\n","<br />")';
Tested it -> works!
I'm sorry but newlines are not acceptable in JavaScript, not sure how your template looks like but if you really cannot replace the newlines by \n or <br> the you can do a trick:
In the template render the contents coming from the database into a hidden div:
<div id="example-text" style="display:none">$question.answer.data</div>
In your javascript code read the contents of the div into your variable:
var exampleText = document.getElementById('example-text').innerHTML;

jquery load content into script tag in firefox

I have an html page using jquery 1.7.2. Within the page I have a scrip tag like so.
<script id="navigation-template" type="text/x-handlebars-template"></script>
Further down the page I'm using javascript to load my handlebars template into the script tag using the following function:
loadTemplate: function( templateId, elementId ) {
if ( !elementId ) {
elementId = templateId;
}
$('#'+elementId).load('/my/path/templates.html #'+templateId);
}
This is working fine in chrome, the eclipse browser, and even IE 9 but seems to go south in Firefox.
I have debugged and the load call successfully completes and the content is returned, but a call to $('#navigation-template').html() gives an empty String.
I also had content in the script tag and called the load and saw that it was replaced by the empty string after the .load call.
Finally, if I manually perform $('#navigation-template').html( "hello" ); I see that the .html() for the script tag is changed.
If I go to a simple ajax get then I will have to parse it and get the given element rather than relying on load to get the element for me.
How do I get around this issue in firefox?
Here is the function I use for such purposes:
Util.loadTemplates = function(ExternalTemplates) {
$.each(ExternalTemplates, function(index, value){
var scriptUrl = value;
$.ajax({
url: scriptUrl,
dataType: 'text',
success: function(res){
var templateName = value.slice(value.lastIndexOf('/') + 1, value.lastIndexOf('.'));
TEMPLATES[templateName] = Handlebars.compile(res);
}
});
});
}
var ExternalTemplates = [
'templates/application.hbs',
'templates/people.hbs'
];
But it is better to look into doing the compiling, which turns the template into a function, before the page is sent to the client.
You are using the type as this
<script id="navigation-template" type="text/x-handlebars-template"></script>
Try changing the type to
<script id="navigation-template" type="text/javascript"></script>
One thing I liked about load() was that I could store all my templates in a single file and use load to select the div for the template I was interested in. I wrote a method that will load the template file and store the templates into a map of template name to template source and compiled template. I compile the template on the first access so that I don't needlessly compile all the templates every time, but only compile the ones I need when needed. It looks something like this:
var myTemplateHelperThingy = {
loadTemplates: function() {
$.get( '/my/path/templates.html' )
.done(function(data) {
var elements = $(data);
$( 'div.template-marker-class', elements).each( function( index, element ) {
// need to use element instead of 'this' because IE is st00pid.
var content = $(element)[0].outerHTML; // trick from StackOverflow
myAppObject.pageTemplates[this.id] = {
source: content,
template: null
};
});
});
},
getTemplate: function( name ) {
// get a compiled template, compiling it if necessary.
var result = myAppObject.pageTemplates[name].template;
if (!result) {
myAppObject.pageTemplates[name].template = Handlebars.compile(myAppObject.pageTemplates[name].source);
}
return myAppObject.pageTemplates[name].template;
},
evalTemplate: function( data, templateName ) {
var template = myAppObject.getTemplate(templateName);
if (template) {
return template(data);
}
else {
// message to user here that something went wrong.
}
},
showTemplate: function( targetElement, data, templateName ) {
$(targetElement).html(bi.evalTemplate( data, templateName ));
}
}
And templates.html looks like:
<html>
<body>
<div id="templates-wrapper-do-not-remove-or-jquery-will-not-find-the-templates">
<div id="my-first-template" class="template-marker-class other-class">
<!-- a bunch of content -->
</div>
<div id="my-second-template" class="template-marker-class another-class">
<!-- more content -->
</div>
</div>
</body>
</html>

javascript validate zip regular expression

Thanks guys. I take your advice and modify the script as following. Now it seems working.
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script>
$(function(){
var pat=/^[0-9]{5}$/;
if ( !pat.test( $('#zip').val() ) )
{$('#zip').after('<p>zip is invalid</p>');}
})
</script>
zip (US only) <input type="text" name='zip' id='zip' maxlength="5">
.val needs to be .val()
and use .after() or .before() and not .append()
var pattern = /^[0-9]{5}$/;
if (!pattern.test($('#zip').val())) {
$('#zip').after('<p>zip is invalid</p>');
}
zip is invalid should be enclosed in quotes
and .val needs to be .val()
<script>
pattern=/^[0-9]{5}$/;
if (!pattern.test( $('#zip').val() ) )
{
$('#zip').val($('<p>',{html: "zip is invalid"}));
}
</script>
Space it out so you can see what's wrong..
pattern=/^[0-9]{5}$/;
if (
!pattern.test( $('#zip').val() )
)
{
$('#zip').after(
$('<p>',{html: "zip is invalid"})
);
}
val() and "zip is valid". Also, the var is useless unless within a function scope.
(function() {
var pattern=/^[0-9]{5}$/;
if (
!pattern.test( $('#zip').val() )
)
{
$('#zip').after(
$('<p>',{html: "zip is invalid"})
);
}
})();
Now pattern is local to that function only and nothing else. In CMS's example it's still a global unless you're taking the snippet and using it in an actual function.

Categories