Be Right Bacon
Be Right Bacon

Reputation: 75

Duplicate Form Field Inputs

I'm attempting to duplicate a form input entry. Is it possible specify a specific input and output field using ID or class with Javascript?

In this example I am trying to duplicate the entry from id1 and have it output to uniqueid. However, all fields are affected. How do I specify the ID?

<form>
<input type="text" id="id1" name="" value="" />
<input type="text" id="id2" name="" value="" />
<input type="text" id="uniqueid" value="">
</form>


var $unique = $('input[type="text"]').mousemove(function(){
$unique.val(this.value);
});

Upvotes: 1

Views: 1056

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

I think your wires are a bit crossed here. You can select an element by it's ID using the # selector.

Let's make this a bit more legible by separating it out:

var $id1 = $("#id1");         //Store id1 input
var $unique = $("#uniqueid"); //Store uniqueid input

$id1.mousemove(function() {   //On mousemove event of id1
  $unique.val($(this).val()); //Set unique's value to id1's value
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="id1" name="" value="" />
  <input type="text" id="id2" name="" value="" />
  <input type="text" id="uniqueid" value="">
</form>

As d4nyll mentions in the comments below, if you simply want to update the uniqueid field any time id1 changes, then you should change your .mousemove() to be .keyup() instead.

Upvotes: 2

Related Questions