Javascript - copy text from one field to another using a button - javascript

I am trying to figure out how to insert text from one text field to another using a button.
This is what I have so far:
function copy(ID_value) {
var textToCopy = document.getElementById(ID_value).innerHTML;
var whereToCopy = document.getElementById("text");
whereToCopy.value += textToCopy;
}
HTML
<div id="opt">
<BUTTON id="1"onClick="copy(1);"> Option 1</BUTTON>
<BUTTON id="11"onClick="copy(11);"> Option 2</BUTTON><br>
<BUTTON id="2"onClick="copy(2);"> Option 3</BUTTON> or
<TEXTAREA ID="name" style="height:25px; width:300px;"></TEXTAREA>
<BUTTON id="3"onClick="copy(name);">Send</BUTTON><br>
<BUTTON id="4"onClick="copy(4);"> Option 4</BUTTON>
<BUTTON id="5"onClick="copy(5);"> Option 5</BUTTON>
<BUTTON id="6"onClick="copy(6);"> Option 6</BUTTON>
<BUTTON id="7"onClick="copy(7);"> Option 7</BUTTON>
<BUTTON id="8"onClick="copy(8);"> Option 8</BUTTON>
<BUTTON id="9"onClick="copy(9);"> Option 9</BUTTON>
<BUTTON id="10"onClick="copy(10);"> Option 10</BUTTON>
<p />
</div>
<TEXTAREA ID="text" style="height:100px; width:600px;">
</TEXTAREA>
Just as the buttons work, I need the "Send" button to send the text in the small field, to the large field, in any given order (Just as how each Option button inserts text in to the large field with proper spacing reguardless of order)
Any help would be greatly appreciated.

There are two problems in your question.
1) you are passing name not "name" so it will say name is undefined.
2) Because textbox has property value to get it's content your function is not working.
Leave your copy function as it is. Add one more function copyFromTextBox and call that on send button click.
<BUTTON id="3"onClick="copyFromTextbox();">Send</BUTTON><br>
function copyFromTextbox(id){
var textToCopy = document.getElementById('name').value;
var whereToCopy = document.getElementById("text");
whereToCopy.value += textToCopy;
}

I testing it desktop browsers: Firefox, Chrome, Safari.
<BUTTON id="3"onClick="if(document.getElementById('name').value!='')
text.value+=' '+document.getElementById('name').value">Send</BUTTON>
or
for(i=0;i<10;i++)document.querySelectorAll('button')[i].onclick=function(){
text.value+=this.innerHTML};
snd.onclick=function(){if(document.getElementById('name').value!='')
text.value+=' '+document.getElementById('name').value}
<div id="opt">
<button> Option 1</button>
<button> Option 2</button><br>
<button> Option 3</button> or
<textarea id="name" style="height:25px;width:300px"></textarea>
<input type="button" id="snd" value="Send"/><br>
<button> Option 4</button>
<button> Option 5</button>
<button> Option 6</button>
<button> Option 7</button>
<button> Option 8</button>
<button> Option 9</button>
<button> Option 10</button>
</div>
<br><br><textarea id="text" style="height:100px;width:600px"></textarea>
name. -not work. That question asked Jul 28 '14 at 4:55 Why that question is top on main page?

Your problem here is that your passing a number and not a string to the copy function.
Change copy(1) to copy('1') and things will work.

what you want to do is just copy the value of one text field into another. You can do this:
function copyToAnother()
{
var text1 = document.getElementById(id_of_first_text_field);
var text2 =document.getElementById(id_of_second_text_field);
text2.value = text1.value; // copy value of Ist field into second Field
}
and then on your copy button's onclick action reffer that function.

Try this code,This is a program similar to your question
<html>
<head>
<script>
function copy_data(val){
var a = document.getElementById(val.id).value
document.getElementById("text_to").value=a
}
</script>
</head>
<TEXTAREA ID="text_from" style="height:100px; width:600px;">
</TEXTAREA>
<TEXTAREA ID="text_to" style="height:100px; width:600px;">
</TEXTAREA>
<button onclick=copy_data(text_from)>Copy</button>
<html>

function copy() {
var areaA = document.getElementById("areaA");
var areaB = document.getElementById("areaB");
var valueA = areaA.value;
areaB.value = valueA;
}
just from a quick look you need to add "" to getElementById,
and use .value instead of innerHTML should work find.
here is a example. http://jsfiddle.net/6e67Y/

Related

Clone <div> and change onclick code of inner button

I have a div with id="add-dependent" including 2 rows and a button (add dependent) inside of the div. When "add dependent" button is clicked, the first row would be cloned and insert before (add dependent) button. Actually I have another button outside of the div called (add applicant) and by clicking it, whole of the div would be cloned and added before (add applicant) button. my code is like this :
let nextLabel=2
let nextId=1
function addApplicant(){
var elem= document.querySelector("#add-dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("add-applicant");
clone.id = "add-dependent"+nextLabel;
elem.parentElement.insertBefore(clone,add);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove" onClick="$(this).parent().parent().parent().parent().remove()">x</button>' + "Applicant " + (nextLabel++) ;
}
function addDependent(){
var elem= document.querySelector(".dependent");
var clone=elem.cloneNode(true);
var add= document.getElementById("dependent");
elem.parentElement.insertBefore(clone,add);
var label=clone.querySelector('label');
label.innerHTML= '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" onClick="$(this).parent().parent().parent().remove();" >x</button>';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="add-dependent">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div >
<input type="number" placeholder="age">
</div>
</div>
<div class="form-row dependent">
<div>
<button id="btn" name="btn" type="button" class="close " onClick="$(this).parent().parent().remove();" >x</button>
</div>
<div>
<input type="number" placeholder="age">
</div>
</div>
<button id="dependent" onClick="addDependent()">Add dependent</button>
</div>
<button id="add-applicant" onClick="addApplicant()">Add applicant</button>
my problem is when i click on (add dependent) in cloned div, the row is added to main div not cloned one.
hope to here you soon.
Thanks a lot
There are many changes I made to your code and I'll try to explain them here. When you're working with duplicating, appending, removing etc, id's can become difficult to work with - you can't have duplicates of IDs and your code then has to track which id is affected by which button etc.
Its much easier to work with relative paths. For instance when you want to add a dependent, it's easier to say 'find a dependent input to clone and place it inside the container from where I clicked this add-dependent button' - and walla no need for ids. To find the relative div's, I used a combination of event.target, closest() and querySelctor - like this:
e.target
.closest('.add-applicant-container')
.querySelector('.dependents')
.append(clone);
This says Starting from the button I clicked, find the closest '.add-applicant-container' and inside that find the first '.dependents' and place our clone right after that
Finally, the buttons. Because you're creating and destroying these buttons in the process, it's best to set up a listener on document and test to see which button was clicked. This is called event delegation. For the dependent delete button, we only need to find the relative element and delete it so:
if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
let nextLabel = 2
let nextId = 1
document.addEventListener('click', function(e) {
if (e.target.classList.contains('add-applicant')) {
addApplicant(e)
} else if (e.target.classList.contains('btn-dependent')) {
addDependent(e)
} else if (e.target.classList.contains('remove-applicant')) {
e.target.closest('.add-applicant-container').remove()
} else if (e.target.classList.contains('close')) {
e.target.closest('.dependent-container').remove()
}
})
function addApplicant(e) {
let applicant = document.querySelector('.add-applicant-container')
var clone = applicant.cloneNode(true);
clone.id = "add-dependent" + nextLabel;
clone.querySelectorAll('.dependent-container').forEach((el, i) => {
if (i !== 0) el.remove()
})
applicant.parentElement.insertBefore(clone, e.target);
var label = clone.querySelector("label");
label.innerHTML = '<button class="close remove-applicant">x</button>' + "Applicant " + (nextLabel++);
}
function addDependent(e) {
let dependent = document.querySelector('.dependent-container')
var clone = dependent.cloneNode(true);
e.target.closest('.add-applicant-container').querySelector('.dependents').append(clone);
// var label = clone.querySelector('label');
// label.innerHTML = '<button id="btn" name="btn" type="button" class="close float-left" style="font-size:12px;" >x</button>';
}
.add-applicant-container{
padding:10px;
}
.dependent-container{
padding:5px 0 ;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add-applicant-container">
<div class="form-row dependents">
<div>
<label class="text-left" contenteditable="true">Applicant 1: </label>
</div>
<div>
<input type="number" placeholder="applicant age">
</div>
</div>
<div class="form-row dependent-container">
<div>
<input type="number" placeholder="dependent age"> <button id="btn" name="btn" type="button" class="close ">x</button>
</div>
</div>
<button class="btn-dependent">Add dependent</button>
</div>
<button class="add-applicant">Add applicant</button>

Call previous sibling as function parameter?

I'm building a wee letter-writing tool that will have a range of paragraphs the user can choose to add to a letter, but I worry that I'm doing it in a really inefficient way.
Currently, it's structured like this:
<p id="deposit-dispute" class="paragraph">This is a paragraph about deposits not being protected</p>
<button onclick="addPara(depositDispute)" class="add">Add paragraph</button>
and then in the Javascript, I create a const that pulls the inner HTML of that id:
const depositDispute = "\n" + document.getElementById("deposit-dispute").innerHTML + "\n";
which the addPara() function then adds to the textarea:
function addPara(text) {
document.getElementById("text-body").value += text;
}
But would there be a way to make the function just call whatever the previous p element had in it, rather than having to give them all unique IDs and creating a unique variable for them all?
Here it is in a codepen so you can see what I'm trying to do - the paragraphs to be added are in the accordion on the right: https://codepen.io/gordonmaloney/pen/GRWyjOP
Thanks a lot - and big apologies if this is a ridiculously amateurish question, I've spent ages trying to google a solution but can't find a thing!
G
Each box contains a paragraph and a button.
We can get all the boxes and each box paragraph and button, and finally add click event to the button to insert the paragraph html of this box to the textarea
// Get textarea and boxes
var textarea = document.getElementById('textarea');
var boxes = document.querySelectorAll('.box');
// get the button and the paragraph of each box
boxes.forEach(box => {
var btn = box.querySelector('.button');
var paragraph = box.querySelector('.paragraph');
// add the html of the selected box paragraph to the textarea
btn.addEventListener('click', () => {
textarea.value += "\n" + paragraph.innerHTML; + "\n";
});
});
<div class="wrapper">
<div class="box">
<p class="paragraph">This is paragraph 1</p>
<button class="button">Add to textarea</button>
</div>
<div class="box">
<p class="paragraph">This is paragraph 2</p>
<button class="button">Add to textarea</button>
</div>
<div class="box">
<p class="paragraph">This is paragraph 3</p>
<button class="button">Add to textarea</button>
</div>
</div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

How do do you edit HTML form elements’ in jQuery?

I’m trying to make a simple font generator for a challenge. The form element I’m trying to edit is the tag.
The way this webpage is supposed to work is a user types in the “input textbox”, presses one of the 3 buttons and the new text will appear in the “output textbox” in the font that the user chooses.
This is what my HTML looks like:
<div id=“inputContainer”>
<p id=“inputText style=“text-decoration:underline;position:relative;”>Input</p>
<textarea id=“input” rows=“10” columns=“10”></textarea>
</div>
<div id=“outputContainer”>
<p id=“outputText” style=“text-decoration:underline;position:relative;”>Output</p>
<textarea id=“output” rows=“10” columns=10”></textarea>
</div>
And here is my jQuery/JS:
var inputText = $("#input").html();
$("#monospaceButton").click(function() {
$("#output").html(inputText);
});
The function only works if I manually add text between the tags (innerHTML). When the user types in the textarea in the code’s output (The website.), there will be no output in the “output” textarea.
I appreciate any help. Please let me know if I need to explain anything more clearly. Thanks!
$("#button1").click(function() {
var value = $("#input").val();
$("#output").css('font-family', 'serif');
$("#output").val(value);
});
$("#button2").click(function() {
var value = $("#input").val();
$("#output").css('font-family', 'monospace');
$("#output").val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p id="inputText" style="text-decoration:underline;position:relative;">Input</p>
<textarea id="input" rows="3" columns="10"></textarea>
</div>
<button id="button1">Style 1</button>
<button id="button2">Style 2</button>
<div>
<p id="outputText" style="text-decoration:underline;position:relative;">Output</p>
<textarea id="output" rows="3" columns="10"></textarea>
</div>

How to update fields dynamically in Javascript?

<button onclick="myFunction()">Set demo1</button>
<button onclick="myFunction()">Set demo2</button>
<button onclick="myFunction()">Set demo3</button>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
This is the markup I have. I am trying to use just one function to update the <p> tags individually.
Example Scenario: Clicking Set demo1 button will only update the <p> which has id="demo1" but with only one function.
Help would be very much appreciated.
You can use following approach. Clicking on each button will affect corresponding p element.
var elems = document.getElementsByClassName('btn');
Array.from(elems).forEach(v => v.addEventListener('click', function(){
var index = this.innerHTML.match(/\d+/)[0];
var elem = document.getElementById('demo'+index);
// logic
elem.style.color = 'red'; // just an example
}));
<button class='btn'>Set demo1</button>
<button class='btn'>Set demo2</button>
<button class='btn'>Set demo3</button>
<p id="demo1">1</p>
<p id="demo2">2</p>
<p id="demo3">3</p>
If you change your markup slightly so that each button has a data-target attribute, then it can be easily done.
HTML:
<button onclick="myFunction()" data-target="#demo1">Set demo1</button>
<button onclick="myFunction()" data-target="#demo2">Set demo2</button>
<button onclick="myFunction()" data-target="#demo3">Set demo3</button>
JS
function myFunction() {
var pTag = document.getElementById(this.getAttribute('data-target'));
pTag.textContent = "Hello world"; // whatever you would like
}

Use JavaScript and a button to calculate new value using user generated values

I'm still very new to javascript, so sorry is this is a basic question. I've tried doing this several different ways, and have researched but can't quite find what I'm trying to do.
What I want to do is calculate the value of the product of two user created fields (hPlayed and hDealt) when the user clicks a button. The values for hp and hd have been previously generated by the user using a button. In my script they have variable names of hPlayed and bDealt, but in the below code I'm creating new variables called hPlayedInput and hDealtInput to represent them (which I realize may not be necessary, but I've tried using just those variables with a console.log as well).
Modified JS:
function handsPlayedRate() {
var hPlayedInput = document.getElementById("hp").value;
var hDealtInput = document.getElementById("hd").value;
var hRate = parseFloat(hPlayedInput) / parseFloat(hDealtInput);
document.getElementById("hr").innerHTML = hRate;
}
FULL (MODIFIED) HTML:
<button class="btnlost" onclick="handsPlayedMinus()">-</button>
<button class="btnwon" onclick="handsPlayedPlus()">+</button>
<p class="count" id="hp">0</p>
<button class="btnlost" onclick="handsDealtMinus()">-</button>
<button class="btnwon" onclick="handsDealtPlus()">+</button>
<p class="count" id="hd">0</p>
<button class="btnreset" type="button" onclick="handsPlayedRate()">Calculate Percent</button>
<p class="count" id="hr">0</p>
Since the values you needed are not in an input field, you need to use .innerHTML to get the value.
function handsPlayedRate() {
var hPlayedInput = document.getElementById("hp").innerHTML;
var hDealtInput = document.getElementById("hd").innerHTML;
var hRate = parseFloat(hPlayedInput) / parseFloat(hDealtInput);
document.getElementById("hr").innerHTML = hRate;
}
<button class="btnlost" onclick="handsPlayedMinus()">-</button>
<button class="btnwon" onclick="handsPlayedPlus()">+</button>
<p class="count" id="hp">1</p>
<button class="btnlost" onclick="handsDealtMinus()">-</button>
<button class="btnwon" onclick="handsDealtPlus()">+</button>
<p class="count" id="hd">2</p>
<button class="btnreset" type="button" onclick="handsPlayedRate()">Calculate Percent</button>
<p class="count" id="hr">0</p>

Categories

Resources