how to update value in textarea after clicking a button? - javascript

I'm practicing JavaScript creating a convert case where I have a textarea where the initial text is informed and the second where the converted result should be output, I created a function to invert the text but when I click on the button that calls this function it doesn't convert if there is already a typed text.
How do I get it to update the values ​​when I click on the button?
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>
I want to create other conversion functions so I want the value the user has already typed to be converted as soon as he clicks on one of the conversion options.

If I understand your question you want the button to directly convert the text. Right now you code is doing the reverse, but update the input only after user type a key.
You want to revert instantly on button click, and keep the update going
function reverseText(){
function reverse(s){
var word = '';
for (var i = s.length - 1; i >= 0; i--)
word += s[i];
return word;
}
function updateInput() {
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
}
$('#input1').keyup(updateInput);
updateInput();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="convert-case">
<textarea id='input1'></textarea>
<textarea id='input2' readonly></textarea>
</div>
<div class="function-button">
<button onclick="reverseText()">reverse text</button>
</div>

I don't really get what you want. If you want to get the value from input1, reverse the text and put it into input2 then just remove the first and last line of the code below
$('#input1').keyup(function(){
var text = $('#input1').val();
var newstring = reverse(text);
$('#input2').val(newstring);
});

Related

Taking only first string from paste value in input value [duplicate]

This question already has answers here:
Get first word of string
(12 answers)
Closed 1 year ago.
I want to get only the first value from copy-paste value.
For example:
my copy text is: Lorem Lipsum Test
So when I copied this above text and paste it into the HTML input filed there need to come only "Lorem" I don't need other text
Is there any way to achieve these things?
Thanks in advance.
it only returns always the first word from string input and you have to clear for copy new value then it's show first word of the new copied string.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#getfirstword").on("keyup", function(e) {
debugger
// do stuff!
var str = $(this).val();
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
var firstWord ="";
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
firstWord = str1[i].split(' ')[0];
}
$("#input1").val(firstWord);
})
});
</script>
</head>
<body>
<input id="getfirstword" />
<input id="input1" disabled/>
</body>
</html>
You can add an input event to see what you are trying to add to your element. This code will split your pasted text and only add the first word.
const input = document.querySelector('input');
const log = document.getElementById('values');
input.addEventListener('input', updateValue);
var previousValue = "";
function updateValue(e) {
log.textContent = e.data;
if (e.data && e.inputType == "insertFromPaste") {
if (e.data.length > 1) {
let val = e.data.split(" ")[0];
let str = previousValue + val;
e.target.value = str;
}
}
previousValue = e.target.value;
}
<input placeholder="Enter some text" name="name"/>
<p id="values"></p>

Javascript check if input is a specific string

I have an HTML Input field and I need javascript to check if the input entered into this box is a certain string. Specifically, it has to be a specific Zip code, there are a total of 9 different zip codes, all which are different and in no numerical order. Once the code checks if it is that specific zip code, it returns "Yes", if not, simply no.
I know how to do this with ints, as shown in the code below, but not sure to how to do this with strings. This is my current code, which works with validating an integer between 1-10:
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I think you are over-thinking this. You can just use the indexOf function to test your zip code array.
var btn= document.getElementById("btn");
var input = document.getElementById("numb");
var output = document.getElementById("demo");
var formArea = document.getElementById("formArea");
var zips = ["11111","22222","33333","44444","55555", "e1", "e2"];
btn.addEventListener("click", function() {
var result = null;
// indexOf() returns -1 when the supplied value isn't present
if(zips.indexOf(numb.value.toLowerCase()) > -1){
result = "yes";
// Show the form by removing the hidden class
formArea.classList.remove("hidden");
} else {
result = "no";
// Hide the form by adding the hidden class
formArea.classList.add("hidden");
}
output.textContent = result;
});
#formArea{
border:2px double grey;
width:50%;
box-shadow:2px 2px 0 #303030;
height:100px;
padding:5px;
}
.hidden {
display:none;
}
<input id="numb">
<button type="button" id="btn">Submit</button>
<p id="demo"></p>
<div id="formArea" class="hidden ">
Your form goes here
</div>
Can you use a regular expression for postal codes? Note this accounts for a set of zip codes that are in string format, but you are welcome to create a zip-code regex that can satisfy the set of zip codes you are interested in. And furthermore, if the set is small enough you can probably just enumerate them in a list/set and check if the set contains the input.
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (!isValidZip.test(x)) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
convert it to a number
x = Number(document.getElementById("numb").value);

Nothing appears on console in chrome,taking information from form

I'm creating a simple string reverse project.
I want the user to enter input, then that input will be displayed below the text box in reverse order.
<form id = "frm1">
<input type="text" id="userInput"=> give me input</input>
<button onclick="strRev()">Submit</button>
</form>
<script type="text/javascript">
function strRev(str){
str = document.getElementById("userInput").toString().value;
console.log(str);
var originalStr = str.split("");
console.log(originalStr);
var finalArray = [];
var j = 0;
for(i = originalStr.length-1; i >= 0; i--){
finalArray[j] = originalStr[i];
j++;
}
for(k = 0; k <finalArray.length; k++){
document.write(finalArray[k]);
}
}
</script>
When pressing submit, the information in the box is what should be reversed
Nothing happens on submit and nothing appears in console to debug.
Try the below code:
str = document.getElementById("userInput").value;
onclick="strRev()"
and you are calling
function strRev(str) // function with one argument, must be showing error in console
Add type="button" in your button input, that way the form won't refresh
<button type=button onclick="strRev()">Submit</button>
You will probably be able to continue solving your other problems after that.
You have an error in your html here <input type="text" id="userInput"=>
it should be <input type="text" id="userInput">
also fetching the value of input should be like this
str = document.getElementById("userInput").value;
After applying these changes you will see the output in console

Displaying new input value (adding spaces)

This seems embarrassing to ask even for a newbie like me, but I have a huge headache with displaying new value in the html input field after adding spaces between numbers in html input.
Basically, what I want to achieve is to add spaces between numbers in the input field after the user "unclicks" the input.
For example, 123456789123456789 would change to 12 3456 7891 2345 6789. I get the value of users input and add spaces where I want, but I just can't make it appear in the input field. My code looks like this:
'use strict';
$(document).ready(function (){var $inputTwo = $('#separateNumbers');
$inputTwo.change(function() {
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4){
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
})
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="number" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
I don't understand why this doesn't work. I tried to replace last code line with
document.getElementById('separateNumbers').value = displayNumber;
but then I got this in console:
The specified value "87 6178 1" is not a valid number.
The value must match to the following regular expression:
-?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?.
This appears no matter what combination of numbers I put. Unfortunately I don't understand Regex yet, so I don't even know what would be a valid value...
a number does not have spaces in it. change your input to a type = text and it should work
change the type to text because adding space not work in the text format
$(document).ready(function() {
// Displaying new input value (adding spaces) -- Solution
$("#separateNumbers").change(function() {
$inputTwo = $('#separateNumbers');
var inputNumber = $inputTwo.val();
var separatedNumbers = [];
var part1 = inputNumber.substring(0, 2);
separatedNumbers.push(part1);
for (var i = 2; i < inputNumber.length; i += 4) {
separatedNumbers.push(inputNumber.substring(i, i + 4))
}
var displayNumber = separatedNumbers.join(' ');
$inputTwo.val(displayNumber);
});
});
<body>
<div class="wrapper">
<div id="Task1_2">
<h1>Task 1.2</h1>
<label for="separateNumbers">Write more than 10 digits:</label><br/>
<input type="text" id="separateNumbers" placeholder=" i.e. 12345678901234567">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

Categories

Resources