Textarea past one after one on click - javascript

I need to do the following:
Copy one column with some values to textarea.
Textarea copies one line at a time after click on button
Pastes the copied value into the second textarea, one line after the other, without overwriting (not the whole one, only one by one)
Here is my testing code:
<textarea id="txt1" rows="10" cols="100" readonly="readonly"></textarea>
<textarea id="txt" rows="4" cols="50" onclick="eraseText()"></textarea>
<input type="button" onclick="displayOut()" value="click">
<script type="text/javascript">
function eraseText() {
document.getElementById("txt").value = "";
}
function displayOut() {
var input = document.getElementById("txt").value;
var text2 = document.getElementById("txt1");
text2.value = input;
if (input.length === 0) {
alert("Please enter a valid input");
return;
}
eraseText();
}
</script>

Your question was a bit unclear but gave it a try anyway.
function eraseText() {
document.getElementById("txt").value = "";
}
function displayOut() {
var input = document.getElementById("txt").value.trim().split('\n').map((line) => line.substr(0, 1)).join('\n');
var text2 = document.getElementById("txt1");
text2.value = text2.value.length ? [ text2.value, input ].join('\n') : input;
if (input.length === 0) {
alert("Please enter a valid input");
return;
}
eraseText();
}
<textarea id="txt1" rows="10" cols="100" readonly="readonly"></textarea>
<textarea id="txt" rows="4" cols="50" onclick="eraseText()"></textarea>
<input type="button" onclick="displayOut()" value="click">

Related

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
}

showing the length of a input

How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.

Not able to disable comma in textarea

Below is the code where textarea will be created automatically. But i want to disable comma in this textarea,so i am using the below javascript function.
$(document).ready(function(){
var counter = 1;
var val;
$("#addButton").click(function () {
var person = prompt("Please enter the Field name:", "");
if (person == null || person == "") {
return false;
} else {
val = person;
}
if(tabid == "menu4"){
return false;
}
//alert(tabid);
var newTextBoxDiv0 = $(document.createElement('div'))
.attr("class", 'form-group row')
.attr("id",'form1ac' + counter);
newTextBoxDiv0.after().html('<div class="col-xs-1"><input type="button" value="delete" onclick= rem(form1ac'+counter+')></div><div class="col-xs-1"><button type="button" class="btn btn" name="" id="buttonl" style="width: 170px;height:45px;background-color:#dcdcdc;color:black;">'+val+'</button><input type="hidden" name="buttonl" form="form1" value='+val+'></div><div class="col-xs-2"></div><div class="col-xs-4"><div class="form-group"><textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea></div><input form="form1" type="hidden" name="tabid" value='+tabid+'></div>');
newTextBoxDiv0.appendTo('#'+tabid);
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#form1ac" + counter).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
The above jquery code will dynamically create new textarea with label option,which works perfectly. But i am trying to disable comma with the above mentioned javascript code which is not working perfectly.
Please help me!
If you want to prevent user to type a comma:
<textarea class="no-comma"></textarea>
And
$(function() {
$('textarea.no-comma').on('keydown', function(e) {
if (e.keyCode == 188 || e.keyCode == 110) { // thats a comma
e.preventDefault();
}
}).on('change input', function() {
var self = $(this);
self.html( self.html().replace(new RegExp(',', 'g'),'') ); // Remove all commas.
});
})
Your html has a syntax error "2")" >
Should be '2')" >
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, '2')" ></textarea>
In place of below code
<textarea form="form1" name="df" id="df" oninput = "this.value = this.value.replace(/[,]/g, "2")" ></textarea>
use below code
<textarea form="form1" name="df" id="df" oninput = 'this.value = this.value.replace(/[,]/g, "2")' ></textarea>

Paste multiple text lines into multiple html input boxes

I am looking for a way to let the users copy e.g. a multi-line address paste it into a webpage where there is one input field for each address line in such a way that not only the first line is pasted, but instead the program automatically jumps to the next field and put line 2 in there and so on.
Below is the code I managed to find, But it's limited to word counts.. In the below code it's 1.. Is there any way which won't limit by word count but by line count
<input type="text" class="text-input" name="box1">
<input type="text" class="text-input" name="box2">
function handleCharacter(event) {
var $input = $(this),
index = getIndex($input),
digit = $input.val().slice(0,1),
rest = $input.val().slice(1),
$next;
if (rest.length > 0) {
$input.val(digit); // trim input value to just one character
$next = $('.text-input[name="chars['+ (index + 1) +']"]');
if ($next.length > 0) {
$next.val(rest); // push the rest of the value into the next input
$next.focus();
handleCharacter.call($next, event); // run the same code on the next input
}
}
}
function handleBackspace(event) {
var $input = $(this),
index = getIndex($input),
$prev;
// if the user pressed backspace and the input is empty
if (event.which === 8 && !$(this).val()) {
$prev = $('.def-txt-input[name="chars['+ (index - 1) +']"]');
$prev.focus();
}
}
function getIndex($input) {
return parseInt($input.attr('name').split(/[\[\]]/)[1], 10);
}
$('.def-txt-input')
.on('keyup', handleCharacter)
.on('keydown', handleBackspace);
Thanks in advance for your help!!!!
I provided a textarea to paste stuff and then split the lines and pasted in other boxes.
<textarea class="def-txt-input" id="mainbox">
</textarea>
<br/>
<input type="text" class="text-input" name="box1">
<input type="text" class="text-input" name="box2">
<input type="text" class="text-input" name="box3">
<input type="text" class="text-input" name="box4">
<input type="text" class="text-input" name="box5">
<input type="text" class="text-input" name="box6">
<script>
function handleCharacter(event) {
var longString = $("#mainbox").val();
var ks = $('#mainbox').val().split("\n");
//e.preventDefault();
var inputs = $(".text-input");
$.each(ks, function(k){
//alert(ks[k]);
//alert(inputs[k].name);
var thisName = inputs[k].name;
//$("[name='box1']").val('hi');
$('[name="' + thisName + '"]').val(ks[k]);
});
console.log(longString);
}
$('.def-txt-input')
.on('keyup', handleCharacter);
// .on('keydown', handleBackspace);
</script>

Adding bullet points to multiple textareas with same 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.

Categories