Unable to get text from ace.js-div in express.js - javascript

I'm using ace.js(https://github.com/ajaxorg/ace) to create a snippet-editor. The html looks like this:
<div id="editor" name="editor">{{ text }}</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
</script>
When I've changed the text, I would like to save to a mongoose-db. But I'm not able to get the text from the editor in my post-request. How do I get the text from the div when I call the save-request?
router.route("/home/save/:id")
.post(function(request, response) {
console.log(request.body.editor) // -> undefined
console.log(request.body) // -> {}
});

Sorry for the perhaps fussy question. Had a hard time explaining the problem. But if anyone for some reason get in the same situation, I solved it by making a kind of a lazy solution.
I took inspiration from https://jsfiddle.net/deepumohanp/tGF6y/ and got the text from the ace-div and placed it in an input. Then I just got the input from the next request:
{{> nav }}
<div id="editor">{{ text }}</div>
<form action="/home/save/{{ this.sessionId }}" method="post">
<input type="text" value="" name="content" id="content">
<button>Save</button>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<script>
var textarea = document.querySelector("#content");
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
console.log(textarea.value);
console.log(editor.getSession().getValue());
editor.getSession().on("change", function () {
textarea.value = editor.getSession().getValue();
});
textarea.value = editor.getSession().getValue();
</script>
That way, the request.body.content returned with the text:
router.route("/home/save/:id")
.post(function(request, response) {
console.log(request.body.content) // -> text
});

Related

Question on id="imgClickAndChange" and onclick="copy_password().."

I want to have a picture when clicked, change from image 1 > image 2 > image 3 > back to image 1. And at the same time when they click it, it copies a hidden caption belonging to the picture that says "COPY THIS TEXT". I used the code, which I will place below of this post. It seems to work when I run it here. But when I place it on my website, it doesnt work.
So what I did is I went to inspect elemet and to console. It throws out a Uncaught SyntaxError: Unexpected token '<' on the places where I start the code with a script command. Im not interested in using a .js input, just want a html edit.
Im not sure what Im doing wrong. Could someone look into the code for me? Im not every experienced with Javascript.
It seems to run okay when I test the code on jfiddle or W3schools Try it editor.
Currently, I just need the javascript to work on one portion of just one of my post entry and Not the whole website. It is very specific to that section. Im currently pasting the code in wordpress under: Create Post >> Text Tab
as an html input (i.e. just copied and paste the code below).
The kind people here have managed to help me get the image to toggle. However, it is not able to copy the text. Can anyone help? It states ReferenceError: copypass is not defined
Here is the code below
<html>
<body>
<p>
<img src='http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png' id="imgClickAndChange" onclick="copy_password() ; changeImage()"/>
</p>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png") {
document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
}
else if (document.getElementById("imgClickAndChange").src == "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png") {
document.getElementById("imgClickAndChange").src = "https://secureservercdn.net/166.62.112.199/smt.db9.myftpupload.com/wp-content/uploads/2012/06/Number-3-bright.png";
}
else if (document.getElementById("imgClickAndChange").src == "https://secureservercdn.net/166.62.112.199/smt.db9.myftpupload.com/wp-content/uploads/2012/06/Number-3-bright.png") {
document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
}
}
</script>
<center>
<p hidden> <span id="pwd_spn" class="password-span">COPY THIS TEXT</span></p>
<script>
document.getElementById("cp_btn").addEventListener("click", copy_password);
function copy_password() {
var copyText = document.getElementById("pwd_spn");
var textArea = document.createElement("textarea");
textArea.value = copyText.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
}
</script>
</body>
</html>
i didn't fully understand you , but i tweaked your code , it working fine for me i hope it works for you too
by the way make sure the scripts are above if you are going to change so you don't get that the fuctions aren't declared
<html>
<head>
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png") {
document.getElementById("imgClickAndChange").src = "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png";
}
else if (document.getElementById("imgClickAndChange").src == "http://www.wpclipart.com/education/animal_numbers/animal_number_2.png") {
document.getElementById("imgClickAndChange").src = "https://secureservercdn.net/166.62.112.199/smt.db9.myftpupload.com/wp-content/uploads/2012/06/Number-3-bright.png";
}
else if (document.getElementById("imgClickAndChange").src == "https://secureservercdn.net/166.62.112.199/smt.db9.myftpupload.com/wp-content/uploads/2012/06/Number-3-bright.png") {
document.getElementById("imgClickAndChange").src = "http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png";
}
}
function copypass() {
let copyText = document.getElementById("pwd_spn");
let pass = copyText.textContent;
let textArea = document.createElement("textarea");
textArea.value = pass;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
}
</script>
</head>
<body>
<p>
<img src='http://www.clipartbest.com/cliparts/RiA/66K/RiA66KbMT.png' id="imgClickAndChange" onclick="changeImage() ; copypass()"/>
</p>
<p hidden> <span id="pwd_spn" class="password-span">COPY THIS TEXT</span></p>
</body>
</html>
you should clear all the tags
<p> and </p>

Can't display language variables in javascript code using mustache.js

I'm trying to handle translations with Mustache.js and it works fine for some part of the code but not for another part.
<script>
function MyFunction() {
// If a submit button is pressed, do some stuff and run this function to display the result
var tmpText = "";
tmpText = "<b>{{someTextInJSfunction}}</b>"; // this is NOT OK
document.getElementById("totalText").innerHTML = tmpText;
}
</script>
</head>
<body>
<div id="sampleArea">
</div>
<script id="personTpl" type="text/template">
<span id="totalText"></span></p>
<b>{{ImpNotice}}</b> {{Contact}} // this is OK
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/mustache.js"></script>
<script>
$( document ).ready(function() {
var lang = 'en_us';
$.getJSON('json/'+lang+'.json', function(data) {
var template = $('#personTpl').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
});
</script>
When I click a Submit button, my JS function is called and depending on some calculation, some text should be displayed in the page. This is the part that doesn't work, {{someTextInJSfunction}} is displayed instead of the actual content of {{someTextInJSfunction}}.
The content of {{ImpNotice}} and {{Contact}} is correctly displayed because I assume the variables are located in the <script id="personTpl"> tags.
I'm not sure how to fix it for the variables located in my JS functions, such as {{someTextInJSfunction}}.

document.getElementById doesn't get newly entered HTML text input value

I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.
first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}
If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}

Switching pages after Zeroclipboard copies text

I've seen quite a few posts about zeroclipboard, but unfortunately the replies have not been helpful (understandable) to a script newbie like me. I have a page with a bunch of coupons on it. When someone clicks on a coupon, I want to copy the coupon's CODE and then take them to the coupon's LINK. I can get the CODE to copy in the alert, but I can't figure out how to then take them to the url I specify in each coupon's LINK. Can someone show me a way to do this? Here's my code...
<section style="position:relative">
<div id="sliders" style="margin:0 auto; width: auto; height:auto;">
<div class="scrollable" id="scrollable">
<div id="slider1" class="items">
<div onclick="window.open('http://url-one.com','_blank');"> <!--THERE ARE SEVERAL OF THESE-->
html...
<div id="clip_container1">
<p id="coupon1" link="url-one.com" onMouseOver="move_swf(this)">copytext1</p>
</div>
</div>
</div>
</div>
</div>
</section>
<script>
ZeroClipboard.setMoviePath( '<?= base_url("resource/js/ZeroClipboard.swf");?>' );
var clip = null;
// function $(id) { return document.getElementById(id); } //not needed?
function init()
{
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
clip.addEventListener('complete', function(client, text) {
alert("Copied Coupon Code to your clipboard:\n" + text);
// now open "link" in a new window...;
});
}
function move_swf(ee)
{
copything = document.getElementById(ee.id+"").innerHTML;
clip.setText(copything.substring(23));
if (clip.div)
{
clip.receiveEvent('mouseout', null);
clip.reposition(ee.id);
}
else{ clip.glue(ee.id);
}
clip.receiveEvent('mouseover', null);
}
window.onload = init;
</script>
Fetch the desired DOM element by the coupon code it contains
(assuming coupon codes are unique)
Add something like this below the alert code:
(assuming jquery in the lines of code I added):
clip.addEventListener('complete', function(client, text) {
alert("Copied Coupon Code to your clipboard:\n" + text);
//Add the two lines below
var mylink = jQuery( "p:contains(" + text + ")" ).attr('link');
myWhateverOpenSesameFunctionToOpenMyLink(mylink);
});

Javascript DOM failing when moving a CKEditor node

I need to be able to swap CKEditor rich text areas throughout my webpage. My current script works great when there's no CKEditor applied, but does not successfully move the text area (and entered text) when CKEditor is applied. Here's some code(it needs ckeditor to work):
<html>
<head>
<title>Sample - CKEditor</title>
<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
</head>
<body>
<form method="post">
<p>
My Editor:<br />
first link
<textarea name="editor1"><p>Initial value.</p></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
</script>
</p>
<p>
My Editor2:<br />
<textarea name="editor2"><p>Initial value2.</p></textarea>
<script type="text/javascript">
CKEDITOR.replace( 'editor2' );
</script>
</p>
<p>
<input type="submit" />
</p>
</form>
</body>
</html>
<script>
function swap(from, to){
if(from && to){
var parent = from.parentNode;
var t;
if(parent){
t = parent.removeChild(from);
parent.insertBefore(t, to);
t = null;
}
delete(t);
delete(parent);
}
}
</script>
If you comment out the CKEDITOR.replace() calls, there's no problem doing the swap. Any suggestions for how I can fix this? Thanks.
Turns out it's a bug. http://cksource.com/forums/viewtopic.php?t=18417
You have to destroy instances do your dom move and then apply CKEDITOR again
something like
var target = $( evt.target ).closest('.root');
var next = target.next();
var cke = target.find('.cke' ).attr('id')
cke = cke.replace('cke_','');
CKEDITOR.instances[cke].destroy();
var cke = next.find('.cke' ).attr('id')
cke = cke.replace('cke_','');
CKEDITOR.instances[cke].destroy();
next.after(target);
CKEDITOR.replace( $( 'textarea' , target)[0] ,{height: '250px'});
CKEDITOR.replace( $( 'textarea' , next)[0] ,{height: '250px'});
Here is my method, using jQuery.
My context: I want to move "div1" after "div2". Each DIV contains a textarea with CKEditor.
<div id="div1"><textarea id="txt1">Bla bla</textarea></div>
<div id="div2"><textarea id="txt2">Lorem ipsum</textarea></div>
<script>
CKEDITOR.replace('txt1');
CKEDITOR.replace('txt2');
</script>
Then, to move "div1" after "div2":
<script>
var current = $('#div1');
var next = current.next();//Same as $("div2")
//Remove instance of CKE
//but first, get the data from the wysiwyg editor
//(what you have typed can be lost)
var CKEinstance1 = CKEDITOR.instances['txt1'];
$('#txt1').html(CKEinstance1.getData());
CKEDITOR.remove(CKEinstance1);
//Also remove the wysiwyg from the DOM
//Its ID is always prefixed by "cke_" and followed by the textarea ID
$('#cke_txt1').remove();
//Move Div1 after Div2
current.insertAfter(next);
//Rebind CKE to txt1
CKEDITOR.replace('txt1');
</script>

Categories

Resources