javascript take selected text in textarea - javascript

I trying todo a simple BB code for my textarea. My code works fine, but it not takes selected text. Example: TEXT. If i select with mouse on TEXT ant choose the [B] tag it does not update text to: [b]TEXT[/b]. It writes after TEXT. Example: TEXT[b][/b]. Any suggest?
<script type="text/javascript">
function formatText(tag) {
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value += '' + tag + '';
}
</script>
<i class="fas fa-bold"></i>

You were just adding your tag at the end but you want the tag to wrap the selected text. then, You can do it like this. Also, edited the HTML code accordingly.
function formatText(tag) {
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt+'['+tag+']' +selected_txt +'[/' +tag+']' + after_txt;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<i class="fas fa-bold">Click</i>
<textarea id="text">I trying todo a simple BB code for my textarea. My code works fine, but it not takes selected text. Example: TEXT. If i select with mouse on TEXT ant choose the [B] tag it does not update text to: [b]TEXT[/b]. It writes after TEXT. Example: TEXT[b][/b]. Any suggest?</textarea>
</body>
</html>

first split the tag so that we get [b] and [/b]
the rest of your code is good.
tested here https://jsfiddle.net/x0tfyna9/12/ on chrome
<body>
<textarea id="text"></textarea>
<i class="fas fa-bold">xasada</i>
<script>
function formatText(tag) {
var tags = tag.split("]", 2).map(function(t) {
return t + "]";
});
var Field = document.getElementById('text');
var val = Field.value;
var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
var before_txt = val.substring(0, Field.selectionStart);
var after_txt = val.substring(Field.selectionEnd, val.length);
Field.value = before_txt + tags[0] + selected_txt + tags[1] + after_txt;
}
</script>
</body>

Related

Add and Delete text using 2 buttons in javascript (conditions : use div id 'divResult' , console log.)

I want to make a webpage with 2 buttons (Add, Delete). Conditions are using div id divResult , console log and after removing that div has to stay. It works almost correct, just last step (remove alinea) doesn`t work. Can you help me , how can i fix it? :-)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>2 buttons</title>
<script >
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement')
var alinea = oldDiv.querySelectorAll('p:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
oldDiv.removeChild(alinea);
console.log('verwijderd!');
};
};
</script>
</head>
<body>
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
</body>
</html>
I've tried a few things, moved stuff around. I think it's doing what you want now.
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement');
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
alinea.remove();
// divResult.removeChild(alinea);
console.log('verwijderd!');
};
};
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
If I understand you correctly, change the following section:
document.getElementById('Btn2').onclick = function () {
var alinea = document.getElementById('div'+ --index);
console.log(alinea.innerHTML + ' wordt verwijderd...');
alinea.remove(alinea);
console.log('verwijderd!');
};

get info by tag name in Javascript

I need a way to capture all the text fields of unknown quantity and save them as a JSON: I'm pretty comfortable coding but new to web. Is this even the way to do it? thanks!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="myP">
field
<br />
</div>
<button onclick="addField()">add field</button>
<button onclick="captureAllInfo()">Capture</button>
<script>
var whichdiv = 0;
function addField() {
whichdiv = whichdiv + 1;
parentDocument = document.getElementById("myP");
var mydiv = document.createElement("div");
mydiv.id = whichdiv;
var input1 = document.createElement("input");
var label1 = document.createElement("label");
label1.innerHTML = "input label 1 ";
input1.id = "Info1";
var input2 = document.createElement("input");
var label2 = document.createElement("label");
label2.innerHTML = "imput label 2";
input2.id = "Info2";
mydiv.appendChild(label1);
mydiv.appendChild(input1);
mydiv.appendChild(label2);
mydiv.appendChild(input2);
parentDocument.appendChild(mydiv);
}
function captureAllInfo() {
for (var i = 0; i < whichdiv; i++) {
console.log("loopin");
var thisDiv = document.getElementById(i);
console.log(thisDiv.getElementById("Info1").value);
}
}
</script>
</body>
</html>
Really what I would like to do is get those two inputs and then add them to a JSON object like
JSON STRUCTURE as below:
{
"1":
{input1 : "string",
input2: "String"},
"2":
{input1 : "string",
input2: "String"}
"3"...,
"4"...
}
We have a function like this document.querySelectorAll('input').
This will fetch all the input elements that exist in your DOM. And then you can modify them as per your requirement.
Please forgive the bad formatting of my function. I wrote this on my fairphone2. The idea is that I used className for the repeated identifiers. Please also note that purely numeric id tags should be avoided.
<html>
<div id="myP">
field
<br />
</div>
<button onclick="addField()">add field</button>
<button onclick="captureAllInfo()">Capture</button>
<script>
var whichdiv = 0;
function addField() {
whichdiv = whichdiv + 1;
parentDocument = document.getElementById("myP");
var mydiv = document.createElement("div");
mydiv.id = 'd'+whichdiv;
mydiv.className='idiv';
var input1 = document.createElement("input");
var label1 = document.createElement("label");
label1.innerHTML = "input label 1 ";
input1.className = "Info1";
var input2 = document.createElement("input");
var label2 = document.createElement("label");
label2.innerHTML = "input label 2";
input2.className = "Info2";
mydiv.appendChild(label1);
mydiv.appendChild(input1);
mydiv.appendChild(label2);
mydiv.appendChild(input2);
parentDocument.appendChild(mydiv);
}
function qsa(s,o){return [...(o||document).querySelectorAll(s)]}
function captureAllInfo() {var o={};
qsa('.idiv').forEach(d=>{
var c=o[d.id.substr(1)]={};
qsa('input',d).forEach(t=>c[t.className]=t.value);
});
console.log(JSON.stringify(o));
}
</script>
</html>
Edit:.
I added the shortcut function qsa() for the various "QuerySelectorAll" methods to make everything a bit more readable. qsa() returns an Array instead of a simple nodelist. The second argument in qsa() is optional. If given it will be the element for which the .querySelectorAll() method will be called. It defaults to document.

undefined after declaring the variable

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>moving word</title>
</head>
<body>
<p id="word">w3resource</p>
</body>
</html>
<script type="text/javascript" src="five.js"></script>
function MovingLetters() {
var text = document.getElementById("word").value;
var len = text.length;
var lastletter = text.charAt(len-1);
text = text.substring(0,len-1);
text = lastletter + text;
}
MovingLetters();
$(function() {
setInterval(MovingLetters, 1000);
});
Console gives me :
Cannot read property 'length' of undefined
No idea why it is undefined because I defined it 2 lines before that one while that one reflects to a <p> in the html code that runs before the js script runs. Can someone help?
using value is for input elements, you should use textContent, innerText or if you want the html innerHTML:
var text = document.getElementById("word").textContent;
function MovingLetters() {
var word = document.getElementById("word")
var text = word.textContent;
var len = text.length;
var lastletter = text.charAt(len - 1);
text = text.substring(0, len - 1);
text = lastletter + text;
word.textContent = text
}
MovingLetters();
setInterval(MovingLetters, 1000);
<p id="word">w3resource</p>
You dont't want the value you want what's called innerHTML. you can achieve this by doing document.getElementById("word").innerHTML.length.

function is not working in my code

my problem is that text3 is undefined in my codes in here:
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
but it is here:
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
here is all of my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
</script>
</body>
</html>
what is the problem?
please help
Looks like $('#x').keyup() is being called before $('#pass').keyup()
Your call $('#x').keyup(function (e) { is creating the first event listener so on keyup you will always endup with text3 is undefined because the $('#pass').keyup(function (e) { will be triggered always later.
EDIT:
Your second keyup handler will never work because it will grab the #pass element only once (during document parse). You need to create some defered listener to fix it.
// Anyway this won't fix your text3 is undefined problem.
What you need to do is define it first before the two .keyup handlers.
NOTE:
But please avoid setting global variables anyway ;)
Put everything into a closure or something.
Last but not least DO NOT create many elements with the same ID this is a major bug.
Look, even after fixing the code to get it to work it makes very little sense. Using roryok's jsFiddle, it'll only work if the value you're entering is a number and doing so just spawns the paragraph elements for the number you entered. You can enter as many numbers as you'd like (before your browser crashes), it'll always return as "weak".
If it's a simple password strength meter you're after, unless you can explain the logic you're trying to achieve more by forcing it to stick to numbers, I'd dump most of the JavaScript code and reduce it to
$('#x').keyup(function (e) {
document.getElementById("passdiv").innerHTML = strength($(this).val());
return true;
});
function strength(val) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test(val)) {
t = "strong";
} else if (normal.test(val)) {
t = "normal";
} else {
t = "weak";
}
return t;
}
This will then validate the whole input each time you enter a character, which the user can then submit once it's "strong".
Here's my jsFiddle: http://jsfiddle.net/xqooj482/
text3 is not set as a variable in your code, therefore it's always going to be undefined. You need to set it before your two functions.
Note: I also put things inside a jQuery ready function.
For some reason I'm being downvoted, but I tested this and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p><input placeholder="number of tests" type="text" name="numbers" id="x"/></p>
<div id="passdiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
// set text3 in here first
var text3 = "";
$('#x').keyup(function (e) {
var i;
var text2 = '';
var t = "";
var x = document.getElementById("x").value;
for (i = 1; i <= x; i++) {
text2 = '<p><input placeholder="test NO. ' + i + '" type="password" id="pass" /></p>';
t += text2 + "Case #" + i + ":" + "<br>" + text3 + "<br>";
}
document.getElementById("passdiv").innerHTML = t;
return true;
});
$('#pass').keyup(function (e) {
var strong = new RegExp("^(?=.{11,})(((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*\\W))|((?=.*[a-z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[0-9])(?=.*\\W))|((?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]))).*$", "g");
var normal = new RegExp("^(?=.{4,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[a-z])(?=.*\\W))|((?=.*[0-9])(?=.*\\W))).*$", "g");
if (strong.test($(this).val())) {
text3 = "strong";
} else if (normal.test($(this).val())) {
text3 = "normal";
} else {
text3 = "weak";
}
return true;
});
});
</script>
</body>
</html>
Also here's a fiddle of it working
http://jsfiddle.net/gsuy4t27/

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Categories

Resources