CKEDITOR: get data from multiple instance names in Javascript - javascript

Because I have multiple textareas in HTML code, I pass the id value through Javascript to retrieve the data in each textareas. However, in the JS function, the "CKEDITOR.instances.id" doesn't represent as expected such as CKEDITOR.instances.editor_1, CKEDITOR.instances.editor_2, or CKEDITOR.instances.editor_4, therefore, I don't have any data retrieved. Anyone knows how to fix this please let me. Heaps of thanks.
HTML code:
<textarea name="edit_1"></textarea>
<input type="button" value="submit" onClick="getValue('edit_1')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_2')" />
<textarea name="edit_2"></textarea>
<input type="button" value="submit" onClick="getValue('edit_3')" />
JS code:
var getValue = function(id) {
var content = CKEDITOR.instances.id.getData();
alert(content);
};

Try adding [] between id
var getValue = function(id) {
var content = CKEDITOR.instances[id].getData();
alert(content);
};

i had to do something like this as i was binding events to actions with multiple instances.
and trying to get the data but it would always return null for any one but the last... using the event (e.editor) worked though.
var editors = CKEDITOR.instances;
for (var x in editors) {
if (editors[x]) {
var thisName = editors[x].name;
if (editors[thisName]) {
editors[thisName].on('focus', function (e) {
socket.emit('ckeditor_field_type_edit', user, e.editor.name);
});
editors[thisName].on('key', function (e) {
var data = e.editor.getData();
socket.emit('ckeditor_field_type_typing', user, e.editor.name, data);
});
editors[thisName].on('blur', function (e) {
var data = e.editor.getData();
setTimeout(function () {
socket.emit('ckeditor_field_type_edit_finish', user, e.editor.name, data);
}, 1000);
});
}
}
}

Related

How to call function inside Javascript

<script type="text/javascript>
function submitMe() {
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
}
</script>
<input type="hidden" name="jsfields" id="jsfields" value="">
I'm searching the way to get checked Ids of Jstree in form submit. So this is what I get. However, how I can call this function in my program?
Use a click/submit event
$(form).submit(submitMe);
or
$('[type="submit"]').click(submitMe);
Don't forget to prevent the default event and then trigger it after the code:
function submitMe(e) {
e.preventDefault();
var checked_ids = [];
$('#your-tree-id').jstree('get_checked',null,true).each(function(){
checked_ids.push(this.id);
});
//setting to hidden field
document.getElementById('jsfields').value = checked_ids.join(',');
window.location = $(this).closest('form').submit();
}

trying to figure out why jsonp request does not work on form request

I have two jsonp requests going to a 3rd party. My first attempt, https://jsfiddle.net/8k3f7b1v/13/ does not run. Console reads, 'cannot perform addEventListner on null'
I looked it over a few times and can't seem to figure out why it's breaking in that specific area. Why is the form null.
Here is a working version, https://jsfiddle.net/8k3f7b1v/12/ from someone else. Both forms use makeUrl with a query from searchField, yet I'm not understanding why this works and not the other one.
HTML
<form id="search-container-form">
<label for="search">Search <input id="search" type="text"></label>
<input type="submit" value="GO">
</form>
<h1>
Output
</h1>
<div id="output">
</div>
//non working fiddle JS
var form = document.getElementById('search-container-form')
var searchField
function defaultUrl() {
return 'https://api.twitch.tv/kraken/search/streams?q=mario&callback=appendResults'
}
function makeUrl(query) {
return `https://api.twitch.tv/kraken/search/streams?q=${query}&callback=appendResults`
}
function getJSON(url) {
var script = document.createElement('script')
script.src = defaultUrl()
script.onload = function() {
this.remove()
}
var head = document.getElementsByTagName('head')[0]
head.insertBefore(script, null)
}
form.addEventListener('submit', function(e) {
e.preventDefault()
var searchField = document.getElementById('search').value
getJSON(makeUrl(searchField))
})
getJSON(defaultUrl())
window.appendResults = function(data) {
console.log(data)
}

How to get ckeditor textarea value using jquery?

I am using ckeditor on textarea but i could not get data from it.
Code :
<textarea name="DSC" class="materialize-textarea"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
Jquery :
var title = $('input[name=TITLE]').val();
var desc = $('textarea[name=DSC]').text();
var formdata = 'TITLE='+title+'&DSC='+desc;
No need for jQuery CKEditor has its own method to get data from converted textarea:
var desc = CKEDITOR.instances['DSC'].getData();
OR:
var desc = CKEDITOR.instances.DSC.getData();
Use id attibute in textarea and use that id in CKeditor instead of textarea's name check bellow
<textarea name="textareaname" id="textarea-id"></textarea>
CKEDITOR.replace( 'textarea-id');//use id not name//
var ckValue = CKEDITOR.instances["textarea-id"].getData(); or
var ckValue = CKEDITOR.instances.textarea-id.getData();
alert(CKEDITOR.instances.DSC.getData());
Past Text area id below.
CKEDITOR.instances['Text_Area_Id_Here'].getData();
For example, i have text area
<textarea class="form-control" id="Description" name="description" width="100%" height="150" ckeditor="true" maxlength="20000" ismandatory="false">
</textarea>
I got value of text area like this
var description = CKEDITOR.instances['Description'].getData();
Using the jQuery_Adapter you may write:
$(function () {
$('textarea[name="DSC"]').ckeditor();
$('#btn').on('click', function(e) {
console.log('ckeditor content: ' + $('textarea[name="DSC"]').val());
})
});
Include files:
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/ckeditor/4.5.9/adapters/jquery.js"></script>
HTML:
<textarea name="DSC" class="materialize-textarea"></textarea>
<button id="btn">Get text</button>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<button type="button" id="getDataBtn">Get Data</button>
</form>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
$(document).ready(function(){
$("#getDataBtn").click(function(){
var editorData= CKEDITOR.instances['editor1'].getData();
alert(" your data is :"+editorData);
})
});
</script>
//getting data form ckeditor in textarea.
var NodeDataSessionTextarea = {};
jQuery('.class-textarea').each(function(index, el) {
var editor_id = jQuery(this).attr('id');
var elevalue = jQuery(this).val();
// Getting ckeditor instance.
var editor = CKEDITOR.instances[editor_id];
if (editor) {
editor.on('key', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on('afterCommandExec', function(e) {
var self = this;
setTimeout(function() {
//store data in object with id
NodeDataSessionTextarea[editor_id] = self.getData();
}, 10);
});
editor.on( 'blur', function() {
//store data in session
var nodedataencodetextarea = JSON.stringify(NodeDataSessionTextarea);
sessionStorage.setItem("NodeDataSessionTextarea", nodedataencodetextarea);
});
}
});
//put data in ckeditor.
var editor = CKEDITOR.instances[id];
if (editor) {
editor.setData(getTemplateData);
}
For an update of Bogdan Kuštan's answer using CKEditor 5 (tested in may 2022):
editor.getData() is the new way of getting the Data from the editor.
Here is one common example of using it: filling an hidden field on submitting the form.
import ClassicEditor from '.../src/ckeditor.js';
ClassicEditor
.create('#editor-container')
.then(editor => {
persistForm(editor);
};
function persistForm(editor)
{
document.querySelector('form').addEventListener('submit', (e) => {
document.querySelector('.hidden-input').value = editor.getData();
});
}
This post is also a reminder for myself later.
You should use getData() method to get data from CKEDITOR.
<textarea name="DSC" class="materialize-textarea" id="DSC"></textarea>
<script>
CKEDITOR.replace('DSC');
</script>
//reference the id DSC
var desc = CKEDITOR.instances['DSC'].getData();

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

how to write onblur and onfocus event in javascript?

Question:
<body onload="setBlurFocus()">
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
</body>
I wrote :
function setBlurFocus () {
var user_input = document.getElementById('id_username');
var email = document.getElementById('id_email');
var password = document.getElementById('id_password');
user_input.onblur = userSetBlur();
email.onblur = emailSetBlur();
password.onblur = passSetBlur();
user_input.onfocus = function() {
document.getElementById('id_username').value = ''
}
email.onfocus = function() {
document.getElementById('id_email').value = ''
}
password.onfocus = function() {
document.getElementById('id_password').value = ''
}
}
function userSetBlur() {
document.getElementById('id_username').value = 'Username'
}
function emailSetBlur() {
document.getElementById('id_email').value = 'Email'
}
function passSetBlur() {
document.getElementById('id_password').value = 'Password'
}
Question?
How to generalize or optimized this code?
You can always attach the methods in JavaScript:
function setBlurFocus() {
var user_input = document.getElementById('id_username');
user_input.onblur = someFunction;
// or with an anonymous function:
user_input.onfocus = function() {
// do something
}
}
Read more about traditional event handling and events in general.
Further explanation:
You attached the function setBlurFocus to the load event of the document. This is correct if you have to access DOM elements with JavaScript. The load event is fired when all the elements are created.
If you attach the setBlurFocus() to the blur event of the input field, then the function is only executed when the text box looses focus.
From your question I concluded you don't want set the event handlers in the HTML, but you want to set them form inside the setBlurFocus function.
Regarding your update:
This is wrong:
user_input.onblur = userSetBlur();
This assigns the return value of the function to onblur. You want to assign the function itself, so you have to write:
user_input.onblur = userSetBlur;
The () calls the function. You don't want that (in most cases, there are exceptions, see below).
Furthermore, you don't have to use named functions for onblur and anonymous functions for onfocus. It was just an example, to show you the different possibilities you have. E.g. if you assign an event handler to only one element, then there is no need to define it as extra function. But you have to do this if you want to reuse event handlers.
Here is an improved version:
function setBlurFocus () {
var values = ["Username", "Email", "Password"];
var elements = [
document.getElementById('id_username'),
document.getElementById('id_email'),
document.getElementById('id_password')
];
for(var i = elements.length; i--; ) {
elements[i].onblur = setValue(values[i]);
elements[i].onfocus = emptyValue;
}
}
function setValue(defaultValue) {
return function(){this.value = defaultValue;};
}
function emptyValue() {
this.value = '';
}
this inside the event handlers refers to the element the handler is bound to.
Note: Here setValue returns a function, that is why we call setValue in this case (and not just assign it).
Important note: This will also reset the values to Username etc, if the user entered some data. You have to make sure, that you only reset it if the user has not entered data. Something like:
function setValue(defaultValue) {
return function(){
if(this.value !== "") {
this.value = defaultValue;
}
};
}
and you'd have to define emptyValue similar:
function emptyValue(defaultValue) {
return function(){
if(this.value === defaultValue) {
this.value = "";
}
};
}
Now that I know what you actually want to do, have also a look at HTML5's placeholder attribute.
Well you've tagged it with jquery so this is how to do it in jquery:
function setBlurFocus () {
//do stuff here
}
$('#id_username').blur(setBlurFocus);
or
$('#id_username').blur(function(){
//do stuff here
});
Regarding your update
I using jquery as you tab jquery, the code was bellow , you can check a live sample with this link :
http://jsfiddle.net/e3test/zcGgz/
html code :
<form method="POST" action="#">
<input id="id_username" type="text" name="username" maxlength="100" />
<input type="text" name="email" id="id_email" />
<input type="password" name="password" id="id_password" />
</form>
javascript code :
$(function(){
var selector = {
username: $('#id_username'),
email: $('#id_email'),
password: $('#id_password')
};
for (var x in selector) {
selector[x].focus(function(){
$(this).val('');
}).blur(function(){
$(this).val($(this).attr('name'));
});
}
});
Hope it help.

Categories