How to pass input from one textarea to another's output? - javascript

I just started learning JS again and I've run into this problem while making an app.
I can't pass input from one textarea to second textarea which is output. I want to make the text uppercase on output. I tried to modify code from w3 but I want to make it without button so it looks cleaner.
What I want to achieve:
User writes something in input
His text is copied to output and changed to uppercase letters
HTML
<h3>INPUT</h3>
<textarea id="inputText" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
JS
document.getElementById("inputText") = str;
var res = str.toUpperCase();
document.getElementById("outputText").innerHTML = res;

Not sure what part of your JavaScript that is, but str is not defined. Here's a working version.
const uppercaseEl = document.getElementById('outputText')
function update(el) {
uppercaseEl.value = el.value.toUpperCase()
}
<h3>INPUT</h3>
<textarea id="inputText" oninput="update(this)" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>

Ok so for that you will first have to make some kind of button that will then trigger the script to run so I have done that in the following:
<h3>INPUT</h3>
<textarea id="inputText" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<button onclick="MakeUpper()">Enter</button>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
Then for the script it shall be a normal function:
function MakeUpper() {
var upperCase = document.getElementById("inputText").value;
var upperCase = upperCase.toUpperCase();
document.getElementById("outputText").innerHTML = upperCase;
}
Hope this solved your query also sorry for any bad code formatting as this is my first time answering a question on the website

You can subscribe to the textarea change event
document.querySelector("#inputText").addEventListener("change", (event) => {
document.querySelector("#outputText").textContent = event.target.value;
});
and when that event appears, change the output text's inner text
BUT the change will only appear after the textarea loses focus, so you could react to the keyup event instead, that will make it real-time :)
document.querySelector("#inputText").addEventListener("keyup", (event) => {
document.querySelector("#outputText").textContent = event.target.value;
});
Or you can use your code, where you just swaped sides, forgot the keyword and you want the element's value, not the whole element
let str = document.getElementById("inputText").value;
let res = str.toUpperCase();
document.getElementById("outputText").textContent = res;
Use textContent instead of innerHTML as it's safe
and I use let instead of var, you should too, look it up

Your first assignment isn’t valid; the variable name (str) always goes on the left.
var str = document.getElementById("inputText").value
You also need .value to get the value of the input. More explicitly:
var inputTextarea = document.getElementById("inputText")
var str = inputTextarea.value
Similarly you need to set .value, not .innerText:
var outputTextarea = document.getElementById("outputText")
outputTextarea.value = str
This will run now, but your central problem (it doesn’t update when you type) persists, because your code just runs once when the page loads. So you copy the value of nothing, then your script stops. You need it to run again whenever the input changes, which looks like this:
var inputTextarea = document.getElementById("inputText")
var outputTextarea = document.getElementById("outputText")
function copyText () {
var upper = inputTextarea.value.toUpperCase()
outputTextarea.value = upper
}
inputTextarea.addEventListener('change', copyText)

In the first line of your js you are trying to do a very bad thing. This operation is called assignment. You can assign a value to a variable, but you are trying to the opposite things.
You want to practice, but in order to do that you need to learn some programming theory first: Variables, operators, functions...
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web that would be a good start. Don't skip anything.

Related

Javascript - Select First Input (With ID)

I am writing a script with pure JS and need to select a text input from a page that has a random name each time:
<input type="text" name="N8PkpWeLsNRQBjvwcwKULB57utJx5L2u0Ko" class="form-control" value="">
Normally i would select it using ID like:
var textinput = document.getElementById("myInput1");
There is no ID however, how can i select this element?
As far as i can see it appears to be the only text input on the page.
I planned on setting some text like this:
HTMLInputElement.prototype.setText = function(text) {
this.value = text;
};
var el = document.querySelectorAll('input[type=text]')[0];
el.setText("Hi");
But this does not work for some reason?
You can use document.querySelector(selectors) it returns the first matching element within the document.
document.querySelector('input.form-control[type=text]')
HTMLInputElement.prototype.setText = function(text) {
this.value = text;
};
var textinput = document.querySelector('input.form-control[type=text]');
textinput.setText("Hi, You can no use setText method.");
<input type="text" name="N8PkpWeLsNRQBjvwcwKULB57utJx5L2u0Ko" class="form-control" value="">
To get the first text field use the following.
var txtField=document.querySelectorAll('input[type=text]')[0];
To set the text you could simply do.
txtField.value="your Value";
This way you can select any HTML tag , since you only have 1 input, this should work for you
var input = document.getElementByName('input');
Try this
var x = document.getElementsbyClassname("form-control").getAttribute("value");

how to modify the following script to be able of receive parameters with spaces?

The main idea is to copy three parameters into my fist text area called: text
<textarea cols="70" rows="15" id="text" ></textarea>
to the press my button called: Generate tables,
<button id="generate">Generate tables</button><br>
and getting the result in the second text area called: out1,
I prove it whit the following parameters:
ford volvo bmw
and I got the right result:
"Svolvo|ford~E~bmw" "ford~SNRF"
The problem is that this time I with to receive three parameters but they could contain spaces as follows:
"ford 34" "volbo 45" "bmz 34"
So with this input I would like to produce the following desired output:
"Svolvo 45|ford 34~E~bmw 34" "ford~SNRF"
Note that the first parameter has two blank spaces and i want to preserve it in the output, when is the case, for every parameter,
However with my current regex that is:
/(\S+)\s+(\S+)\s+(\S+)/g
I am getting:
"S34"|"ford~E~"volbo" ""ford~SNRF" "S"bmz|45"~E~34"" "45"~SNRF"
Which is not right, I would like to appreciate any suggestion to fix my function:
var generate = document.getElementById('generate');
var input = document.getElementById('text');
var output = document.getElementById('out1');
generate.onclick = function() {
var text = input.value;
text = text.replace(/(\S+)\s+(\S+)\s+(\S+)/g,
'"S$2|$1~E~$3" "$1~SNRF"');
output.textContent = text;
};
<textarea cols="70" rows="15" id="text"></textarea>
<div cols="3" rows="15" id="out1" style="width:80%; white-space:pre; color:Lime"></div>
<div class="wrapper">
<button id="generate">Generate tables</button>
</div>
You could use this regular expression, which works for the original case, but also for when you have wrapped words in double quotes, in which case the part between quotes is taken as one part:
/(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))/g
The replacement string needs to change to this, as there are now more capture groups:
'"S$3$4|$1$2~E~$5$6" "$1$2~SNRF"'
Explanation
This part identifies one term. It is repeated for the other two terms:
(?:"(.*?)"|(\S+))
This consists of two options split by |. If the string starts and ends with a quote, the first option is taken, else it goes for the second (original) option.
In both cases there is a capture group, but in the first case the double quotes are excluded. The outer brackets are only to tell the | operator what its scope is; it is not captured as a group ((?:).
var generate = document.getElementById('generate');
var input = document.getElementById('text');
var output = document.getElementById('out1');
generate.onclick = function() {
var text = input.value;
text = text.replace(/(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))/g,
'"S$3$4|$1$2~E~$5$6" "$1$2~SNRF"');
output.textContent = text;
};
<textarea style="width:100%" id="text">ford "volbo 45" "bmz 34"</textarea>
<div id="out1" style="width:80%; white-space:pre; color:Lime"></div>
<button id="generate">Generate tables</button>

Javascript run onChange not onLoad

I have a very simple piece of Javascript that works perfectly onLoad, but I need it to work onChange.
My script;
<form action="" method="post" name="product_search">
<p><strong>Existing Part Number:</strong>
<input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()">
<input type="text" name="prodref" id="prodref">
<input type="submit" name="search_Submit" id="search_Submit" value="Submit">
</p>
<div>
<%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
// <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
<script>
function searchValue() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref');
if(c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add) }
else {
n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
document.getElementById("prodref").value = n_ProdRef;
}
</script>
</form>
So, I enter a part number in the first text box, and I want my javascript to run and enter the new value in the second text box, but it doesn't seem to work.
What am I missing?
search does not exist on an HTMLInputElement. You need to use c_ProdRef.value.search.
(Actually, since you're using it in many places as a string, and never as an input, you probably intended to define c_ProdRef as var document.getElementById('v_prodref').value)
You would've seen this error on load as well.
you want onkeyup if it works perfectly onLoad, and you want to start typing in something in textbox 1 and the javascript to run, you dont want onchange
onchange triggers after blur of focused element
onkeyup triggers after you release a keyboard input
Thanks to everyone for their help. After a little tweaking I have managed to get my code working.
function myFunction() {
var add = "NW";
var c_ProdRef = document.getElementById('v_prodref').value;
if (c_ProdRef.search(/GST/i) == -1) {
n_ProdRef = c_ProdRef.concat(add)
} else {
n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
}
document.getElementById("prodref").value = n_ProdRef;
}
Along with #indubitablee suggestion of onKeyup and specifying the .value of my first text field it all works.

Jquery replace string in a textarea

I am trying to replace a string value in textarea while typing in textbox with jquery. I used keypress event to try achieving that. What may be the issue here in this fiddle?
<input type="text" id="textbox" />
<textarea id="txtArea">This is a sample test.</textarea>
jquery code
$("#textbox").keypress(function () {
var txtAreaValue = $('#txtArea').val();
var txtAreaValueAfterreplace = txtAreaValue.replace('sample', $(this).val());
$('#txtArea').val(txtAreaValueAfterreplace);
});
The main problem is that, when using keypress you are getting the value of the input box before it is set, so nothing appears. However even if you change it to keyup you still will only get one value because once 'sample' is replaced it is gone so therefor it cannot be replaced again.
A new logic needs to be considered if you are wanting to replace sample with the full value of the textarea. Consider the following example:
$("#add").click( function () {
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<input type='button' id='add' value='add'>
<textarea id="txtArea">This is a sample test.</textarea>
Or we replace when the user stopped typing
var typing;
$("#textbox").keyup( function () {
// Stop the change from being made since they typed again
clearTimeout(typing);
// They typed, so set the change to queue up in a 3rd of a second
typing = setTimeout(function(){
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
},350);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<textarea id="txtArea">This is a sample test.</textarea>
You want to look for keyup, not keypress (you want to make sure you get the whole string.
You are trying to put the textbox value right? You're looking for the textarea value in line two of the javascript.
If you replace sample on the first key stroke, there won't be anything to replace the second key stroke.
You can simplify lines 3 and 4 into one line.
replace can only be used on a string. So you need to get the value first, if you're going to do it that way. txtAreaValue.val().replace('sample', $(this).val());
Feel free to play around with it on this fiddle: http://jsfiddle.net/snlacks/abc6skp9/
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val("this is a " + txtValue);
});
If you have a longer string, replace might work better, but you still need to store the full string somewhere.
var longString = "some really long string... sample... more...";
$("#txtBox").on('keyup', function () {
var txtValue = $(this).val();
$('#txtArea').val(longString.replace('sample', txtValue);
});

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.
Here is the HTML I am using:
<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
And the Javascript:
var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/
I have made a new JSFiddle: https://jsfiddle.net/5c4j2opc/3/ which works.
I changed type="submit" to type="button" to stop the page refreshing when the button is clicked and moved the word variable to the replaceStory function so it doesn't just get called once at the beginning of the script! Hope this helps.
You have to change two things.
The first is you are using innerHTML in a input element, when you want to access input element you need to get the value not the innerHTML, inputs not have this property.
The second one is that you need to pass the event on the onclick event since if you don't do it you can't cancel the submit action and then the page will be submit it automatically and reload the content. Then after you pass the event you have to apply event.preventDefault which will stop the submit for that button. Other option to avoid this problem would be possible to replace the submit button with a <button> tag or <input type="button"> since not of them will trigger the submit action.
You can see a working example https://jsfiddle.net/5c4j2opc/9/
html -> same you have
javascript
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(e){
replaceStory(word.value);
e.preventDefault();
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
You initialize wordjust in the beginning of the script. Besides, that the input value is not innerHTML, during that time, the value is empty.
As long as the return value is not set explicitly to false, the form will reload the page and overwrite any result.
Change your code:
var originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
var word = document.getElementById('word').value;
replaceStory(word);
return false;
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
originalStory.innerHTML = story;
};
updated fiddle
You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.
Initially you had:
var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.
Finally, for a input node you should get .value rather than .innerHTML to get the inner text
html:
<form>
<label>Word</label><input id="word"></input>
<input type="button" value="submit" id="submitButton"></input>
</form>
<p id="story"> A {userWord goes here} is now part of the story </p>
javascript:
var word = document.getElementById('word'),
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");
button.onclick = function(){
replaceStory(word.value);
};
var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");
return originalStory.innerHTML = story;
};
I advise you to just understand Javascript first, and after then, focus on learning Jquery because it's much more easier and handy.
By the way if you want to do what you said:
You shouldn't use form tag, because you don't want to send something to server-side and you can use div tag as well instead of form tag.
<div>
<label>Word</label>
<input id="word" type="text"></input>
<button id="submitButton">Submit</button>
</div>
<span>A </span><span id="text">{here}</span><span> is now part of the story</span>
Jquery
$('#submitButton').click(function(){
txt = $('#word').val()
$('#text').text(txt);
});
Don't forget to import Jquery Package.
https://jsfiddle.net/softiran/gt8rr5pe/
You could also allow the user to change your story directly. I know this may not use an input tag, but it was very useful to me.
<div id="story">Once upon a time there was a man named
<p id="added" contenteditable="true" title="Click to change">
Bill</p>. He liked to eat tacos.</div>
I used this in a code that changed the name of the main character of a story into a user-selected name and allowed them to download the story. Hope this helps! All the user has to do is click the name "Bill" and they will be able to change the name to anything they want.

Categories

Resources