Melvin
Melvin

Reputation: 339

jQuery append value from textarea to input

While entering input in a Textarea I want the same text to append to an input, i.e. the input has a value of "http://www." and whatever I enter in the textarea I want to be appended to input's value.

Now it always adds the change to the change, e.g.:

(entering google.com in the textarea) it adds: g go goo goog etc. which results in: http://www.ggogoogoog... etc.

what am I doing wrong?

var titleLink = "";
var url = $('#text2');
	
function inputLink(){		
		titleLink = $('#text1').val();
		console.log("changed: " + titleLink);
		var http = url.val();	
		url.val(http + titleLink);
	};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="text1" id="text1" cols="30" rows="10" oninput="inputLink()"></textarea> <br>
<input id="text2" type="text" value="http://www.">

Upvotes: 0

Views: 358

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

The problem is var http = url.val(); this will get the updated input value each time you input .. So

you can use var http = 'http://www.'; instead

var titleLink = "";
var url = $('#text2');
	
function inputLink(){
  titleLink = $('#text1').val();  // get textarea value
  console.log("changed: " + titleLink);
  var http = 'http://www.';  // http is 'http://www.'
  url.val( http + titleLink); // append http + textarea value
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="text1" id="text1" cols="30" rows="10" oninput="inputLink()"></textarea> <br>
<input id="text2" type="text" value="http://www.">

Upvotes: 2

Related Questions