Adding bullet points to multiple textareas with same Javascript - javascript

I found the below code online to add bullet points to a textarea, and it works quite well for a single textarea.
Script
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("input", OnInput, false);
});
}
function OnInput(event) {
char = event.target.value.substr(-1).charCodeAt(0);
nowLen = txt.value.length;
if (nowLen > prevLen.value) {
if (char == CRLF) txt.value = txt.value + BULLET + " ";
if (nowLen == 1) txt.value = BULLET + " " + txt.value;
}
prevLen.value = nowLen;
}
HTML
<body onload="Init ();">
<h4>Automatic bullets in a text box</h4>
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</body>
However, I can't figure out how to create a similar function such that I can use it on multiple textareas.
I would like something where I can pass through the id of the hidden input, so I can specify that way which input to add the bullet points to, but can't get a working solution.
Suggestions/solutions welcome.

Get a list of all textareas and add the event listener
var textareas = document.querySelectorAll('textarea');
[].forEach.call(textareas, function(element) {
element.addEventListener("click", OnInput, false);
});
You can use any valid CSS3 selector to get the desired textareas.
As per your edit:
You can group the elements together so you can access them as a group. Now you can use the input in any way you like.
<div class="some_wrapper">
<textarea id="txt" oninput="OnInput(this, 'prevLen');" rows="15" cols="40"></textarea>
<input type="hidden" id="prevLen" value="0"/>
</div>
var wrappers = document.querySelectorAll('some_wrapper');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
//process "input" to get the desired "id", "class",.....
textarea.addEventListener("click", function(e) {
OnInput(e, input)
}, false);
});

Solution to my query/issue:
Script/app.js:
var CRLF = 10;
var BULLET = String.fromCharCode(45);
function Init() {
var wrappers = document.querySelectorAll('panel-body');
[].forEach.call(wrappers, function(wrapper) {
var textarea = wrapper.querySelector("textarea"),
input = wrapper.querySelector("input");
textarea.addEventListener("input", OnInput(), false);
});
}
function OnInput(ta,inp) {
char = ta.value.substr(-1).charCodeAt(0);
nowLen = ta.value.length;
if (nowLen > inp.value) {
if (char == CRLF) ta.value = ta.value + BULLET + " ";
if (nowLen == 1) ta.value = BULLET + " " + ta.value;
}
inp.value = nowLen;
}
HTML
<body onload="Init ();">
<div class="panel-body">
<h4>Automatic bullets in a text box</h4>
<textarea id="ta1" oninput="OnInput(ta1, pv1);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv1" value="0"/>
<h4>Automatic bullets in a text box</h4>
<textarea id="ta2" oninput="OnInput(ta2,pv2);" rows="15" cols="40"></textarea>
<input type="hidden" id="pv2" value="0"/>
</div>
</body>
The above solution solves the issue of adding bullets to multiple textareas.

Related

Write elements to textarea using jQuery

I want to get a text from a and add some attributes to the text and show it in another when a button is pressed.
Here is a part of my code - If I use console.log() the correct text will be logged, but the append(x) only writes the option[i] value without any HTML codes.
What should be the solution here?
var options;
$(function() {
options = $('div#Thelper2_container textarea').val().split('\n');
$.fillTextArea();
});
$.fillTextArea = function() {
for (let i = 0; i < options.length; i++) {
var y = i + 1;
var x = String('<span class="textToSelect" value="' + y + '"></span>' + options[i] + '</span>\n');
$('div#Thelper4_container textarea').append(x);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Thelper2_container">
<textarea rows="5" cols="100">Line 1
Line 2
</textarea>
</div>
<div id="Thelper4_container">
<textarea rows="5" cols="100"></textarea>
</div>
Use val instead of append. Append is for non-form field container elements
Although you CAN append to a textarea, when you append, you append HTML and not text.
Also you have too many </span>s and spans do not have values. I changed to data-value
Lastly I filter empty lines
const $txtarea = $('#Thelper2_container textarea');
const $output = $('#Thelper4_container textarea');
const splitLines = val => val
.split('\n')
.filter(line => line.trim() !== "") // drop empty lines
.map((line,i) => `<span class="textToSelect" data-value="${i+1}">${line.trim()}</span>`)
.join("\n");
$(function() {
$output.val(splitLines($txtarea.val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Thelper2_container">
<textarea rows="5" cols="100">Line 1
Line 2
</textarea>
</div>
<div id="Thelper4_container">
<textarea rows="5" cols="100"></textarea>
</div>
Try this:
$('div#Thelper4_container textarea').append(document.createTextNode(x));
Please note the 'document.createTextNode'.
You're appending another </span>\n at the end of the string without opening it anywhere.
Try this code and see if it works:
var x = String('<span class="textToSelect" value="' + y + '"></span>' + options[i] + '\n');

How to connect JS functions to checkbox

Hello,
I am making a simple text changer website where I want the user to be able to select what options to use. Right now I have two options; myConvertOption which capitalizes every odd letter in a word and I have myScrambleOption which randomly mixes up each word a bit.
Right now whenever you click on Caps (checkbox_1) it already executes the function where I only want it to execute whenever the user clicks on the "Convert" button + it also puts spaces in between each letter now.
The Scramble button (checkbox_2) doesn't do anything for some reason, except for console logging the change.
JSfiddle: https://jsfiddle.net/MysteriousDuck/hLjytr2p/1/
Any help and suggestions will be greatly appreciated!
P.S I am new to Javascript.
Checkbox event listeners:
checkbox_1.addEventListener('change', function () {
console.log("checkbox_1 changed");
if (this.checked) {
myConvertFunction();
} else {
//Do nothing
}
})
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
myScrambleFunction(text);
} else {
//Do nothing
}
})
Checkbox HTML:
<div class="checkbox">
<input type="checkbox" id="checkbox_1" >
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2" >
<label for="checkbox_2">Scramble</label>
</div>
this works properly..
You just had to add the event on the button and then test which check box was checked, and other little things
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<h1> Text Changer </h1>
<h2> CAPS + randomize letters text changer</h2>
<div class="checkbox">
<input type="checkbox" id="checkbox_1">
<label for="checkbox_1">Caps</label>
</div>
<div class="checkbox">
<input type="checkbox" id="checkbox_2">
<label for="checkbox_2">Scramble</label>
</div>
<textarea type="text" autofocus="true" placeholder="input text" id="inputText" value="Input Value" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="convertText">Convert</button>
<textarea type="text" placeholder="converted text" id="convertedText" value="Clear" readonly="true" spellcheck="false" style="width: 300px;"></textarea>
<button class="button button1" id="copyText">Copy</button>
</div>
<script>
var text = document.getElementById("inputText").value;
var convertText = document.getElementById("convertText");
var checkbox_2 = document.getElementById("checkbox_2");
var checkbox_1 = document.getElementById("checkbox_1");
//Capitalize every odd letter
function myConvertFunction() {
var x = document.getElementById("inputText").value;
var string = "";
for (let i = 0; i < x.length; i++) {
if (i % 2 == 0) {
string = string + x[i].toUpperCase();
} else {
string = string + x[i];;
}
}
return string;
}
//Scramble words
function myScrambleFunction(text) {
let words = text.split(" ");
words = words.map(word => {
if (word.length >= 3) {
return word.split('').sort(() => 0.7 - Math.random()).join('');
}
return word;
});
return words.join(' ');
}
document.getElementById("copyText").addEventListener("click", myCopyFunction);
//Copy textarea output
function myCopyFunction() {
var copyText = document.getElementById("convertedText");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
eraseText();
}
//Delete textarea output
function eraseText() {
document.getElementById("convertedText").value = "";
document.getElementById("inputText").value = "";
document.getElementById("inputText").focus();
}
//don't add the event to the radio buttons (previously checkboxes), add it to the convert button, and in its function test which radio button has been checked
convertText.addEventListener('click', function() {
if (checkbox_1.checked && checkbox_2.checked) {
console.log("doing both options");
document.getElementById("convertedText").value = myScrambleFunction(myConvertFunction());
} else if (checkbox_2.checked) {
console.log("proceeding scrumble");
document.getElementById("convertedText").value = myScrambleFunction(text);
} else if (checkbox_1.checked) {
console.log("proceeding cap");
document.getElementById("convertedText").value = myConvertFunction();
}
})
</script>
</body>
</html>
You're never updating var text.
You need to update it before using it if you want the value to be something other than an empty string.
checkbox_2.addEventListener('change', function () {
console.log("checkbox_2 changed");
if (this.checked) {
text = document.getElementById("inputText").value;
myScrambleFunction(text);
} else {
//Do nothing
}

Replace words in a textarea

I would like to replace certain words by **** in my TEXTAREA but this script does not work. Thank you for your help
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>
<script>
var input = document.getElementById('Body')[0],
output = document.getElementById('Body')[0],
badwords = /\b(test|test2|test3)\b/g;
input.onkeyup = function () {
output.innerHTML = this.value.replace(badwords, function (fullmatch, badword) {
return '<sub>' + new Array(badword.length + 1).join('*') + '</sub>';
});
};
input.onkeyup();
input.focus();
</script>
Here's a working solution, with explanations in the comments:
//remove [0]. getElementById returns an element, not a collection:
var input = document.getElementById('Body'),
output = document.getElementById('Body'),
badwords = /\b(test1|test2|test3)\b/g;
//addEventListener is the best way to add listeners:
input.addEventListener('keyup', function() {
//Change innerHTML to value here:
output.value = this.value.replace(badwords, function (fullmatch, badword) {
//Remove '<sub>...</sub>'. Textareas support text content only.
return new Array(badword.length + 1).join('*');
});
});
input.focus();
<TEXTAREA style="color:black;" name="Body" id="Body" value="" rows="6" cols="60" maxlength="160"></TEXTAREA><br/>

How can I add a max length message with Jquery 'after' to a class of inputs and update it

I'm trying to get Jquery to append ('after') to some (class) of my inputs so the user knows how much more they can type. Is this even possible?
<script>
$(function() {
$(".maxinputmessage") .after("<br><em>(Maximim characters: " + document.getElementById(this).maxLength + ") You have " + ( document.getElementById(this).maxLength - document.getElementById(this).Length) + " characters left.</em>");
});
</script>
with:
<label for="EditPVComment">PV Comments</label>
<textarea class="maxinputmessage" id="EditPVComment" name="EditPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some text here maybe.</textarea>
I got stuck with the maxLength and I would also like to update as they type and tell them how many characters they have left. (Is this to much for Jquery?) Thanks!
Try this. When inserting the element to display the remaining count, I would recommend including a span or a div tag holder that you can use to update the information during "keyup" bind event on the textarea
<label for="EditPVComment">PV Comments</label>
<textarea class="maxinputmessage" id="EditPVComment" name="EditPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some text here maybe.</textarea>
<br>
<label for="EditManPVComment">Man PV Comments</label>
<textarea class="maxinputmessage" id="EditManPVComment" name="EditManPVComment" cols="80" rows="10" maxlength="3000" style="width:400px;">Some Man text here maybe.</textarea>
<script>
$().ready(function(){
var $this = $(".maxinputmessage");
$this.each(function()
{
var charMaxLen = $(this).attr("maxLength");
var charLen = $(this).val().length;
$(this).after("<em>(Maximim characters: " + charMaxLen + ") You have <span>" + (charMaxLen - charLen) + "</span> characters left.</em>");
$(this).on("keyup",function()
{
var charMaxLen = $(this).attr("maxLength");
left = charMaxLen - $(this).val().length;
$(this).next("em").find("span").text(charMaxLen - $(this).val().length);
});
});
});
</script>
Working example : http://jsfiddle.net/rpcwt2ng/4/
HTML
<input type="text" id="ipText" />
Remaining <span id="remaining"></span>
JavaScript
var limit = 50;
$("#ipText").keyup(function() {
$("#remaining").text(limit - $("#ipText").val().length);
});
Working demo here

Removing unchecked checkbox from final code in JS

I creating a HTML generator, I've used checkbox in the form.
In the resulting code, I'm getting the unchecked boxes as ''.
I have the current code setup at http://jsfiddle.net/Rqe6K/ for your review.
How can the final result be achieved so that only the checked box values are part of the text?
<button onclick="toggle('answer','1','','3','')">Click</button> from this the blank space of the respective checkboxes should be removed.
<form id="band" action="#">
<label>Option 1: <input type="text" id="a1o1"><input type="checkbox" id="a1" class="can"></label><br>
<label>Option 2: <input type="text" id="a1o2"><input type="checkbox" id="a2" class="can"></label><br>
<label>Option 3: <input type="text" id="a1o3"> <input type="checkbox" id="a3" class="can"></label><br>
<label>Option 4: <input type="text" id="a1o4"><input type="checkbox" id="a4" class="can"></label><br>
<input type="submit"></input>
</form>
<p>Copy this:</p>
<textarea rows="20" cols="80" id="code"></textarea>
<script type="text/javascript">
window.onload = function() {
document.getElementById('band').onsubmit = function() {
box1 = '';
box2 = '';
box3 = '';
box4 = '';
if (document.getElementById('a1').checked) { box1 = '1'; }
if (document.getElementById('a2').checked) { box2 = '2'; }
if (document.getElementById('a3').checked) { box3 = '3'; }
if (document.getElementById('a4').checked) { box4 = '4'; }
var text="<button onclick=\"toggle(\'answer\',\'"+box1+"'\,\'"+box2+"'\,\'"+box3+"'\,\'"+box4+"'\)\">Click</button>";
document.getElementById('code').value=text;
return false;
}
}
</script>
If you put an ID called a1o1 but then try to find it using a1, it is normal that the browser never find the control.
UPDATE
Not very cool, but works...
http://jsfiddle.net/A6f9r/
UPDATE2
http://jsfiddle.net/v7rfN/
First of all declare the variables instead of making it global.
i.e. var box1='';
Use this logic-
var text="<button onclick=\"toggle(\'answer\',\'";
if(box1!='')
{
text+=box1+"'\,\'";
}
if(box2!='')
{
text+=box2+"'\,\'";
}
if(box3!='')
{
text+=box3+"'\,\'";
}
if(box4!='')
{
text+=box4+"'\)\'";
}
text = text.substring(0, text.length - 2);
text+=")\">Click</button>";
See fiddle-http://jsfiddle.net/Rqe6K/2/
If you can use jQuery I warmly suggest it, since its syntax is concise:
$("#sendAnswer").click(function(){
var answers = $("input[name='answer[]']").map(function(){if(this.checked){return this.id;}}).get();
var text = "<button onclick=\"toggle(\'answer\'," + serializeInputValues(answers) + ")\">Click</button>";
$('#code').val(text);
return false;
})
function serializeInputValues(fields){
var sStr = "";
jQuery.each(fields, function(i, field){
sStr += "'" + field + "', ";
});
return sStr.slice(0, -2);
}
Try this fiddle.
EDIT: With this approach, your answer can grows and your code still remain the same, with your approach you have to add an if for each new checkbox driving you to a potential combinatorial explosion.

Categories