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>
Related
I'm trying to prepare a Javascript function that changes the "selected text" url to fully active HTML Hyperlinks.
My HTML code is:
<html>
<body>
<textarea id="my_input" cols="32" rows="16" textToDisplay>Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<input type="submit" value="[to url]" onclick="make_url('my_input')" />
</body>
</html>
My js function:
<script>
function make_url(my_input) {
var my_input=document.getElementById(my_input);
var selected_text=window.getSelection();
my_input.value=my_input_begin.value + ''+ selected_text +'' + my_input_end.value;
}
</script>
But after selecting https://www.google.pl/?gws_rd=ssl and pressing submit I get empty HTML Hyperlinks. What is wrong? window.getSelection() / document.getSelection() doesn't get the selected text.
The second question is - how to get my_input_begin.value and my_input_end.value or replace only "selected" part of my <textarea> entry?
I've sorted it out. The final Javascript code is:
function text_to_hyperlink(input_id) {
var text_entry = document.getElementById(input_id);
var text_selected;
// for IE
if (document.selection != undefined) {
text_entry.focus();
var sel = document.selection.createRange();
text_selected = sel.text;
}
// others browsers
else if (text_entry.selectionStart != undefined) {
var selection_pos_start = text_entry.selectionStart;
var selection_pos_end = text_entry.selectionEnd;
text_selected = text_entry.value.substring(selection_pos_start, selection_pos_end);
selection_prefix = text_entry.value.substring(0, selection_pos_start);
selection_sufix = text_entry.value.substring(selection_pos_end, text_entry.length );
}
text_entry.value = selection_prefix + '' + text_selected + '' + selection_sufix;
}
I replace all entry text_entry with HTML hyperlink code. But I didn't find how to easy replace the text_selected with text_selected
Final HTML:
<textarea id="my_input" cols="32" rows="16" textToDisplay>Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<input type="submit" value="[url]" onclick="text_to_hyperlink('my_input')"/>
Try this code:
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
</head>
<body>
<textarea id="my_input" cols="32" rows="16" onclick="this.focus();this.select()">Some text with https://www.google.pl/?gws_rd=ssl for simple WYSIWYG function</textarea>
<p id="link"></p>
<input type="button" value="[to url]" onclick="make_url()" />
</body>
Click on the textArea first to get the text selected and then click on [to url] button.
<script>
function make_url() {
var textComponent = document.getElementById("my_input");
var selectedText;
// IE version
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
var link = document.getElementById("link");
var a = document.createElement("a");
var href = document.createTextNode("Link");
a.appendChild(href);
a.setAttribute("href", selectedText);
document.body.appendChild(a);
}
Note: Every time you add new text in the textArea and click on the [to url] button a new hyper link will be generated.Also i have used jquery library to select the so you have to attach it on the page.
Hope it works fine ☻
I have a similar problem to this post when trying to convert my apps script web app to use IFRAME Sandbox. I have converted to 'input = "button"' as suggested.
My web app is a simple form for students to use to sign in and out of a school library. The idea for the app is for it to be as easy as possible for students to use. Students should enter their id number and be able to either click the submit button or hit the enter key. Their ID is then validated before being stored in a spreadsheet and they get a message back saying thanks for signing in or out, or please enter a valid ID Number. Then focus should return to the text box and be cleared, ready for the next student to enter their id.
I had it working as described above using NATIVE mode. When I tried to convert it to IFRAME mode, clicking the button works, but if you hit the enter key everything just disappears and no data goes to the spreadsheet. How can I get hitting the enter key to work the same as clicking the submit button?
index.html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<h3>Please Sign In & Out</h3>
<div id="box" class="frame">
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
<input type="text" name="myID" id="myID" placeholder="Enter your student ID" autocomplete="off">
<input type="button" value="Submit" onmouseup="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
</form>
<span id="thank_you" hidden="true"></span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?!= include('javascript'); ?>
</body>
</html>
javascript.html code:
<script>
function updateInfo(ret){
if(ret[0]){
$( "#thank_you" ).removeClass("error");
$( "#thank_you" ).addClass("valid");
}
else{
$( "#thank_you" ).removeClass("valid");
$( "#thank_you" ).addClass("error");
}
$( "#thank_you" ).text(ret[1]);
$( "#thank_you" ).show("slow");
$( "#signSheet" )[0].reset();
$( "#myID" ).focus();
console.log(ret);
}
</script>
Code.gs code:
//spreadsheet key is needed to access the spreadsheet.
var itemSpreadsheetKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//Open the spreadsheet and get the sheet objects
var openedSS = SpreadsheetApp.openById(itemSpreadsheetKey);
var studentList = openedSS.getSheetByName("Student List");//Spreadsheet must match with sheet name
var studentRecord = openedSS.getSheetByName("Sign In-Out Record");
function doGet() {
var html = HtmlService.createTemplateFromFile('index').evaluate()
.setTitle('Sign In/Out Sheet')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
function include(filename) {
Logger.log('enter include');
Logger.log(filename);
var html = HtmlService.createHtmlOutputFromFile(filename).getContent();
Logger.log(html);
return html;
}
function validateID(form){
var idNum = form.myID;
var valid = false;
var numIdList = studentList.getLastRow()-1; //-1 is to exclude header row
//get the item array
var idArray = studentList.getRange(2,1,numIdList,1).getValues();
i= idArray.length;
while(i--){
if(idArray[i][0]==idNum & idNum!='') {
valid=true;
break;
}
}
if(valid)
return [1, updateRecord(idNum)];
else return [0, "ID number " + idNum + " not recognized. Please enter a valid ID number."];
}
function updateRecord(idNum){
studentRecord.appendRow([idNum]);
var formulas = studentRecord.getRange("B2:D2").getFormulasR1C1();
var lRow = studentRecord.getLastRow();
var range = studentRecord.getRange(lRow, 2, 1, 3);
range.setFormulas(formulas);
var vals = range.getValues();
var now = new Date();
studentRecord.getRange(lRow, 5, 1, 1).setValue(now);
now = Utilities.formatDate(now, "EST", "HH:MM a");
idNum = "Thanks " + vals[0][0] + ", you have signed " + vals[0][2] + " at " + now;
return idNum;
}
Update: I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This solved the the problem for me with a little more tweaking to parts of index.html and Code.gs
I found this post and added the following code to javascript.html:
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
var idVal = $("#myID").val();
google.script.run.withSuccessHandler(updateInfo).validateID(idVal);
return false;
}
});
})
This listens for the enter key and sends the value of the text field to the apps script function. In this case I didn't need to use `event.preventDefault();'
Then I had to adjust the button's onmouseup function to take this.parentNode.myID and change my apps script function to take a value instead of a form object.
You must remove the onsubmit attribute from the <form> tag:
Currently you have:
<form id="signSheet" onsubmit="google.script.run
.withSuccessHandler(updateInfo)
.validateID(this.parentNode)">
Change it to this:
<form id="signSheet">
You already have a call to google.script.run in your button, so leave that.
Good day.
I'm trying to add Google Places Autocomplete on dynamically created inputs using code below:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var container = document.getElementById('AutoComplInputs');
container.innerHTML += "<br>" + _id;
var _elem_for_upd = document.createElement("input");
_elem_for_upd.type = "text";
_elem_for_upd.id = _id;
container.appendChild(_elem_for_upd);
assignAutoCompl(_id);
}
</script>
</head>
<body>
<div id="AutoComplInputs"></div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
But when I press on button, autocomplete works only on last input, and all prevoius become broken. I think that it can be connected to dynamic creation of inputs, as the code below works fine:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
document.getElementById(_id).hidden = false;
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
assignAutoCompl("AutoCompl0");
assignAutoCompl("AutoCompl1");
}
</script>
</head>
<body>
<div id="AutoComplInputs">
<input id="AutoCompl0" type="text" hidden>
<input id="AutoCompl1" type="text" hidden>
</div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
I don't understand what I'm doing wrong ...
Don't use innerHTML to add content to container, you will lose all handlers bound to existing elements.
Use appendChild instead:
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode(_id));
Is there a way to maintain the div scroll position on a postback, without using asp? So far I've only found solutions using asp.
http://blogs.x2line.com/al/articles/156.aspx
<!doctype html>
<html>
<head>
<title></title>
<script language="javascript">
// function saves scroll position
function fScroll(val)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = val.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove(what)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(what).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br>
<div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
.. VERY LONG TEXT GOES HERE
</div>
</form>
</body>
</html>
Maybe this javascript code works for you
function loadScroll ()
{
var m = /[&?]qs\=(\d+)/.exec (document.location);
if (m != null)
myDiv.scrollTop = parseInt (m[1]);
}
function saveScroll ()
{
var form = document.getElementById ("myForm");
var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
form.action += sep + "qs=" + myDiv.scrollTop;
}
Now, you can watch for the "submit" event to save the position in the "action" attribute:
document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
And in your BODY tag...
<body onload="loadScroll ();">
....
</body>
I can't test the code right now, but I think you get the idea.
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>