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>
Related
My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>
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 currently have this code: https://jsbin.com/hocisirovo/edit?html,css,js,output
With the button, it bolds the entire text in the text box. How can I bold only what I select in the text box? The easy way would be to use execCommand but I cannot use that.
Any help is appreciated.
Thanks!
I didn't quite get your question but you could use an editable div to make parts of your text bold.
<html>
<head>
<script>
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
function boldSelected(){
var textBox = document.getElementById("textbox");
var text = textBox.innerHTML;
var boldText = getSelectionText();
var offset1 = text.indexOf(boldText);
var offset2 = offset1 + boldText.length;
var str1 = text.substring(0,offset1);
var str2 = text.substring(offset2,text.length);
textBox.innerHTML=str1+"<b>"+boldText+"</b>"+str2;
}
function undoBold(){
if(document.getElementById("textbox").innerHTML == "<b></b>")
document.getElementById("textbox").innerHTML == "";
}
</script>
</head>
<body>
<div onkeypress="undoBold()" contentEditable="true" id="textbox" style="width:30%; border:1px solid #0a0a0a;padding:3px;"></div></br>
<button onclick="boldSelected()">Bold</button>
</body>
</html>
When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. What am I doing wrong? Is there a better way to do this?
<html>
<head>
<title>Add HTML input with jQuery</title>
<!--
* This code is meant to include the jQuery library v.1.9.1
* from Google API
-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
<script>
$('document').ready(function(){
$('#add').click(function(){
var src = $('#src'); // alert(src);
var trgt = $('#src'); // alert(trgt);
var x = null;
var child = null;
var str = null;
if(null != src.val()){
alert(1);
x = trgt.children().length;
str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';
trgt.html().append(str);
src.val() = null;
}else{
alert('src value is emppty');
}
});
});
</script>
</head>
<body>
<div id="box">
<label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
<div id="trgt">
</div>
</div>
</body>
</html>
var trgt = $('#src'); ... Your source and target selectors are the same.
This var trgt = $('#trgt') is not the only problem I noticed.
There is trgt.html().append(str); which should be trgt.append(str);.
And then src.val() = null;, are you trying to reset the <input> value? You can simply do it with src.val('');
See this jsfiddle.
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>