I have the following code for a jscript implementation of skulpt to run Python in the browser. I have added a "clear" button, and when it is clicked, I want the text inside the textbox, as well as any "run" code, to be deleted/cleared from the screen.
The below shows my attempt (the function "clearit") but it doesn't work. Any suggestions - please post code for that function with an explanation for what I was doing wrong/corrections.
Relevant function
function clearit(){
var prog = document.getElementById("yourcode").value;
mypre.innerHTML = 'TRY SOME NEW CODE';
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
I paste the full code below, because it could be down to the fact that I am putting the function in wrong place. It stops working altogether once I add this function.
Full code (page.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt.min.js" type="text/javascript"></script>
<script src="http://www.skulpt.org/js/skulpt-stdlib.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// output functions are configurable. This one just appends some text
// to a pre element.
function outf(text) {
var mypre = document.getElementById("output");
mypre.innerHTML = mypre.innerHTML + text;
}
function builtinRead(x) {
if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
throw "File not found: '" + x + "'";
return Sk.builtinFiles["files"][x];
}
// Here's everything you need to run a python program in skulpt
// grab the code from your textarea
// get a reference to your pre element for output
// configure the output function
// call Sk.importMainWithBody()
function runit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = '';
Sk.pre = "output";
Sk.configure({output:outf, read:builtinRead});
(Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
var myPromise = Sk.misceval.asyncToPromise(function() {
return Sk.importMainWithBody("<stdin>", false, prog, true);
});
myPromise.then(function(mod) {
console.log('success');
},
function(err) {
console.log(err.toString());
});
}
<script>
function clearit(){
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
</script>
</script>
<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<p>Output below</p>
<button type="button" onclick="clearit()">Clear</button>
<pre id="output" ></pre>
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>
<script src="js/skulpt.min.js" type="text/javascript"></script>
<script src="js/skulpt-stdlib.js" type="text/javascript"></script>
</body>
</html>
I also tried some other iterations of the function, see below.
<script>
function clearit(){
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
mypre.innerHTML = 'TRY SOME NEW CODE';
<textarea id="yourcode" cols="40" rows="10">
print("Hello World")
</textarea>
}
</script>
To clarify: The mypre.innerHtml worked...but not clearing the textbox with the code. The part I want to implement is to clear the textarea. If I remove the part with <textarea id..) etc the code works fine, and also clears the OUTPUT console. I need the next bit (clearing the textarea) working.
You have an un-necessary HTML tag textarea inside your clearit function, which was causing an error (check in console). It is not required since you already have textarea in your HTML block. Try below (It is not full code only clearit implementation):
function clearit() {
var prog = document.getElementById("yourcode").value;
var mypre = document.getElementById("output");
document.getElementById("yourcode").value = '';
}
<h3>Try This</h3>
<form>
<textarea id="yourcode" cols="40" rows="5">
print("Hello World")
</textarea><br />
<button type="button" onclick="runit()">Run</button>
</form>
<p>Output below</p>
<button type="button" onclick="clearit()">Clear</button>
<pre id="output"></pre>
<!-- If you want turtle graphics include a canvas -->
<div id="mycanvas"></div>
</body>
Your function should look like this:
function clearit(){
document.getElementById('yourcode').value = '';
document.getElementById('output').innerHTML = '';
}
You also have too many script tags, remove the ones around the clearit() function.
Related
I have the following piece of code, which changes one line of text in a click of a button:
<!DOCTYPE html>
<html>
<body>
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'This is JavaScript!'">
Click Me!</button>
</body>
</html>
This is quite easy since there is no script, no function needed to handle the button. Now, I want this same button to change back to the first content when I click it again. I assume that now I need to have a function, but not sure how to write it. An ideas?
You don't have to use a function. You could do it with a ternary operator ? and :, or you could even just write an if else statement all on one line.
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML === 'This is JavaScript!' ? document.getElementById('demo').innerHTML = 'Watch this HTML content changes..' : document.getElementById('demo').innerHTML = 'This is JavaScript!';">
Click Me!</button>
However, that is a lot of code to cram into one line and it would be much cleaner in a separate function, as such.
function changeText() {
var demo = document.getElementById('demo');
if (demo.innerHTML === 'This is JavaScript!') {
demo.innerHTML = 'Watch this HTML content changes..';
} else {
demo.innerHTML = 'This is JavaScript!';
}
}
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Well. Although the way you are trying is not the best practice.... But the following way will give you some hope. try to do more research.
function myFunction() {
var x=document.getElementById("demo").innerHTML;
if(x=="A Paragraph."){
document.getElementById("demo").innerHTML="Back Again";}
if(x=="Back Again")
document.getElementById("demo").innerHTML="A Paragraph.";
}
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
More simply, this function works:
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Javascript:
function changeText() {
e = document.getElementById('demo');
e.innerHTML = e.innerHTML == "Watch this HTML content changes.." ? "This is JavaScript!" : "Watch this HTML content changes..";
}
You can see it working at this JS Fiddle: http://jsfiddle.net/0yLb4a3j/
You can have something like a toggle function:
<script type="text/javascript">
function toggleContent() {
var message1 = "This is JavaScript!";
var message2 = "Watch this HTML content changes..";
var element = document.getElementById('demo');
if (element.innerHTML===message1)
element.innerHTML = message2;
else
element.innerHTML = message1;
return false;
}
</script>
You get it called by setting onclick="toggleContent();" on the button.
You could use an IIFE, an array, an incremented counter, and a modulo operator to achieve this.
document.getElementById('button').onclick = (function(){
var demo = document.getElementById('demo');
var text = [demo.textContent,'This is JavaScript!'];
var count = 0;
return function() {
demo.textContent = text[++count % 2];
}
})();
<p id="demo">Watch this HTML content changes..</p>
<button type="button" id="button">Click Me!</button>
var btn = document.getElementById("<btn_id>");
var previous = "";
btn.addEventListener("click", clickHandler);
function clickHandler() {
var demo = document.getElementById("demo");
if (!previous) {
previous = demo.innerHTML;
} else {
demo.innerHTML = "This is JS";
btn.removeEventListener("click", clickHandler);
}
}
first of all , you ll need to do the code in a seperate script, in brief , append the intial text to the div then wheck button clicked, change it to second text, and according to your question you ll need a second button who will change the div text to the intial text , logically that ll give something like tht :
<script>
window.onload = function(){
document.getElementById('demo').innerHTML = 'Watch this HTML content changes..'
}
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = 'This is JavaScript!'
};
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = ''Watch this HTML content changes..'
};
</script>
I am trying to create an array that pass one item waits for a response from my node server from a list.
My data input to JavaScript is from a text area in html then I am trying to send each line one at a time it can only send the next array item when my nodeJS has finished can anyone show me any example's or ways to post an array one item at a time.
instead of in one big chunk like I am getting currently.
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
my full html
<html>
<html>
<head>
<title>Welcome To ....</title>
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body>
</html>
Well, you code seems OK, except the regexp you use.
You should split the string using \n character. You are using \n\r, which is not a Windown line break character sequence.
Window character sequence is \r\n.
See here: http://www.regular-expressions.info/nonprint.html
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>
I have defined a couple of functions inside my javascript which work perfectly, but when I put it inside a prototype it just doesn't seem to work.
wall.html:
<script type="text/javascript" src="Jquery/jquery-1.4.4.js"> </script>
<script type="text/javascript" src="src/CommentManager.js"> </script>
<script type="text/javascript" src="src/Reply.js"> </script>
<script type="text/javascript" src="src/Comment.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
CommentManager();
$("form#newMessage").submit(function(){
var message = $("input#newMessageTxt").val();
var newComment = new Comment(message);
});
});
</script>
</head>
<body>
<div class="message">
<form id="newMessage">>
<input type="text" id="newMessageTxt" height="200px" value="Write a message" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;" />
<input type="submit" value="Submit" ></button>
</form>
</div>
</body>
but the weird part is when I run the debugging tool in googlechrome, the $("form#newMessage").submit doesn't call at all. So Comment(message) is never created (which is where I have set up the prototype functions)
Comment.js:
function Comment(message){
var self = this;
var message = message;
var comment = document.createElement("li");
comment.id = "comment";
comment.textContent = message;
//empty reply field
var replyField = document.createElement("ul");
replyField.id = "replyField";
//create the appropriate buttons
createButtons(comment);
//append the replyField
comment.appendChild(replyField);
//insert into wall
addComment(comment);
//effect after insertion
Effect(comment);
$(comment).mouseleave(function() {mouseOut(comment);});
$(comment).mouseenter(function() {mouseOver(comment);});
return comment;
}
Comment.prototype={
deleteComment : function (comment){
$(comment).fadeOut();
setTimeout(function() {comment.parentNode.removeChild(comment);},500);
},
//there are more methods here
}
Commentmanager.js:
function CommentManager(){
var owner = null;
var wall = document.createElement("ul");
wall.id = "wall";
document.body.appendChild(wall);
return wall;
}
function addComment(comment){
var wall = document.getElementById("wall");
wall.appendChild(comment);
}
Where is createButtons defined? (in Comment.js)?
Also, you you titled that last file as Commentmanager.js, but wall.html has CommentManager.js (notice the capital M in wall.js). I'm assuming that's a typo here in the SO question, but make sure that your filenames on the server match the html script tags.
I need a very simple Javascript on a html page, that will do the following..
Display a text like:
This is a string of text and can be long
then if you mark some of the text with your mouse, the selected text should be inserted and automatically updated into a text field
How can i do it?
Create readonly textarea (you may use CSS to decorate it as simple text block). Then process it's onSelect event to precess selection. You will get something like:
<script language="JavaScript">
function display(txtarea)
{
var sl = (txtarea.value).substring(txtarea.selectionStart, txtarea.selectionEnd);
alert (sl);
}
</script>
<textarea name="entry" onSelect="display(this);">Some text.</textarea>
<script type="text/javascript">
function render(element)
{
var stext = element.value.substring(element.selectionStart, element.selectionEnd);
document.getElementById('selText').value = stext;
}
</script>
<input id="selText" value="" />
<textarea name="entry" onclick="render(this);">This is a string of text and can be long
</textarea>
Hope this helps
Solution with jQuery Based on this link
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var textSelected = function(el, elResult) {
var len = el.val().length;
var textarea = document.getElementById(el.attr("id"));
if($.browser.msie) {
if (document.selection) {
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText(textarea);
stored_range.setEndPoint('EndToEnd', range);
textarea.selectionStart = stored_range.text.length - range.text.length;
textarea.selectionEnd = textarea.selectionStart + range.text.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
} else {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
}
var sel = textarea.value.substring(start, end);
if (sel.length!=0)
elResult.val(sel);
};
$("#text-entry").bind("select", function(){
textSelected($(this), $("#select-text"));
});
});
</script>
</head>
<body>
<input id="select-text" type="text" /><br />
<textarea id="text-entry">text for select</textarea>
</body>
</html>