I am trying to bind a function to the select field when something is pasted into it (it looks like an input field after allowing multiple style and select2:matcher/tokenize) but in IE it always truncates any pasted text which contains a new line character.
<form method="POST" action="/run" class="ui-widget" onsubmit=" return confirmSubmit(this, 'run',true) ">
Editor:
<select name="editor" id="editor" multiple style="width: 200px">
<option>ALL</option>
</select>
<input type="submit" value="Submit">
</form>
bind('paste') does not seem to work on an <select> object so I had to use bind('change')
var unitIds = ["Red","Yellow","Green"];
$.each(unitIds, function(i, f) {
$('select[name="editor"]').append($('<option>').text(f));
});
$('#pastefromclip').select2({
matcher: function(term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) === 0;
},
tokenizer: function(input, selection, callback) {
if (input.indexOf(" ") < 0) return;
var parts = input.split(" ");
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if(part.length > 0){
if (unitIds.indexOf(part) == -1) {
alert('Invalid fields: ' + part);
} else {
callback({
id: part,
text: part
});
}
}
}
}
});
$('#editor').bind('change', function (e) {
var clipped = window.clipboardData.getData('Text');
clipped = clipped.replace(/(\r\n|\n|\r)/gm, " "); //replace newlines with spaces
//$(this).val(clipped); // this doesn't seem to work
var element = document.getElementById('editor');
element.value = clipped; // doesn't seem to work either
return false; //cancel the pasting event
});
Copy and paste the following into the select field:
Red
Yellow
It pastes only 'Red' and shows the matched object. It does not recognise the change function until I select that matched object and it is being tokenized.
After it recognises that change, it runs through the clipboardData and sees both Red and Yellow but it cannot assign the select field with that data.
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/plugins/jquery.jqgrid.showhidecolumnmenu.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery-1.8.3.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery-ui-1.9.2.js"></script>
<script type="text/javascript" src="javascript/toastr.min.js"></script>
<script type="text/javascript" src="javascript/adminConsole.js"></script>
<script type="text/javascript" src="javascript/select2.min.js"></script>
<script type="text/javascript" src="javascript/moment.min.js"></script>
<script type="text/javascript" src="javascript/jqGrid/ui.multiselect.js"></script>
<script type="text/javascript" src="javascript/jqGrid/grid.locale-en.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery.jqGrid.min.js"></script>
use TokenSeparators for multiple inputs
See it Action
$(".js-example-tokenizer").select2({
tags: true,
tokenSeparators: [',', ' ']
})
Please refer the section Automatic tokenization in Select2 Tokenization
Also when Copy paste the options (Red Green ) don't forget to append "," at last
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
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.
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>