I am trying to create "quicklink" option in textarea using which users can insert html tags by directly clicking over them. It is working fine but after I click any quicklink button the cursor moves to the end of the text present in the textarea.
How to keep/focus cursor just after the inserted tag?
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
// Getting closest number for array
// https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
$('#txtarea').click(function(){
var str = $(this).val();
var regex = /\<([a-zA-Z\/]+\>)/gi, result, indices = [];
// Getting positions as array
// https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
var cursorPosition = $(this).prop("selectionStart");
$(this).prop('selectionEnd');
var closestPosition = closest(cursorPosition,indices)
$(this).prop('selectionEnd', closestPosition);
})
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
You can get current cursor position by using following solution:
https://stackoverflow.com/a/1909997/7676742
And increment it by the length of your new added html tag (for instance 3 for <a>) and set position of cursor by using following solution:
https://stackoverflow.com/a/49750025/7676742
I found an easy way to do this:
function quicklink(link){
var linklen=link.length;
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").prop('selectionEnd', cursorPos+linklen);
$("#textarea").focus();
}
Related
I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>
I'm doing a point counter in general and I have no idea how to do it anymore, so I would like to add +1 to the sum on the "=" button and add it only once if someone could help me, I would be grateful
Code: https://pastebin.com/C26VFyev
var result = 0;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + 1);
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
Use a variable for what you add to the sum. Initialize it to 1 for the first time, than change it to 0 for future uses.
var result = 0;
var addition = 1;
function suma() {
var cal1 = parseFloat(document.forms["form1"]["cal1"].value);
var cal2 = parseFloat(document.forms["form1"]["cal2"].value);
var sum = (cal1 + cal2 + addition);
if (addition == 1) {
addition = 0;
}
document.forms["form1"]["sum"].value = sum
result = sum;
}
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form name="form1">
Cal 1:
<input value="0" name="cal1" size="5"><br> Cal2:
<input value="0" name="cal2" size="5"><br>
<input type="button" value="Oblicz" name="add" onClick="suma();"><br> Suma:
<input type="text" name="sum" size="6"><br>
<input type="reset" value="Reset"><br>
</form>
</body>
</html>
I don't know if I have understood the right context of 'storage', but according to some tutorials I used the following Javascript code, to enable a page to locally store (no session) submitted data, but when I close the page and reopen the page, the content do not appear.
script.js
function initiate()
{
var saveButton = document.getElementById('save');
var retrieveButton = document.getElementById('retrieve');
var deleteButton = document.getElementById('delete');
var reviewButton = document.getElementById('review');
saveButton.addEventListener('click', saveItem);
retrieveButton.addEventListener('click', retrieveItem);
deleteButton.addEventListener('click', deleteItem);
reviewButton.addEventListener('click', reviewAll);
}
function saveItem()
{
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage[key] = value;
}
function retrieveItem()
{
var data = document.getElementById('data');
var key = document.getElementById('key').value;
var value = localStorage[key];
data.innerHTML = '<div>' + key + ': ' + value + '</div>';
}
function deleteItem()
{
if (confirm('Delete?'))
{
var key = document.getElementById('key').value;
localStorage.removeItem(key);
data.innerHTML = '<div>Deleted.</div>';
}
}
function reviewAll()
{
for(var i = 0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var value = localStorage[key];
data.innerHTML += '<div>' + key + ': ' + value + '<br></div>';
}
}
addEventListener("load", initiate);
index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="mystyles.css" />
<script src="script.js"></script>
<title>Demo HTML5</title>
</head>
<body>
<section id="formSection">
<form name="dataForm">
<label for="key">Key: </label><br />
<input type="text" id="key" name="key" /> <br />
<label for="value">Value: </label><br />
<textarea name="value" id="value"></textarea><br />
<input type="button" id="save" value="Save" />
<input type="button" id="retrieve" value="Retrieve" />
<input type="button" id="delete" value="Delete" />
<input type="button" id="review" value="Review" />
</form>
</section>
<section id="data">
No data
</section>
</body>
</html>
If you are using the browser in privacy mode, it will clear all localStorage data when you close it.
I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}
I have just started using Phonegap, I wanted to clear the textbox content when the user clicks on the textbox.
HTML:
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
JavaScript
function clear() {
document.getElementsByTagName('input').value = '';
}
But the clear function is not getting called. Also, just tried putting alert in clear()
function(did not help). Everything else working okay. Any help would be appreciated.
Full HTML Code:
<!DOCTYPE html> <html> <head>
<title>Age Calculator</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
alert('welcome');
}
function calAge() {
var x = confirm('Click here to calculate the age');
if(x == true) {
document.getElementById('ageId').style.display = block';
} else {
navigator.app.exitApp(); }
}
function submitValues() {
var todaysDate = new Date();
var y = todaysDate.getFullYear();
var m = todaysDate.getMonth() + 1;
var d = todaysDate.getDate() + 1;
var myYear = document.getElementById('yearVal').value;
var myMonth = document.getElementById('monthVal').value;
var myDate = document.getElementById('dateVal').value;
var myYear = (y-myYear);
var myMonth = (m-myMonth);
var myDate = (d-myDate);
document.getElementById('ageId').style.display = 'none';
document.getElementById('result').innerHTML = 'You are '+myYear+'years '+myMonth+' months and '+myDate + ' days old :-)';
} function clear() { document.getElementsByTagName('input').value = ''; }
</script> </head> <body>
<button onclick="calAge();">Age Calculator</button> <br>
<div id="ageId" style="display:none;">
<b>Please Enter your Date Of Birth in (dd/mm/yyyy) format:</b>
<input type="text" class="clear" id="dateVal" name="date" value="date" onblur="clear();"/>/
<input type="text" class="clear" id="monthVal" name="month" value="month" />/
<input type="text" class="clear" id="yearVal" name="year" value="year" />
<input type="button" value="submit" onclick = "submitValues();" />
</div>
<div id="result">
</div> </body> </html>
In HTML5 there is a placeholder attribute.
Ex:
<input type="text" placeholder="Enter Date" id="dateVal" name="date" />
We could use this to get what I desired.
Thanks, might be helpful to somebody.