Icewine
Icewine

Reputation: 1851

How to copy value from one text input to another with javascript using a link

I have searched and found ways to do this with checkboxes but i would like to use a link.

I have worked out this much of the code but I know I must be missing something simple.

Anyone have any ideas?

SCRIPT

$(document).ready( function() {
    $("#currencyBtn a").click(function(){
       var value = $('#currencyVal');
       var input = $('.currencyCopy');
       input.val(value);
    });
});

HTML

MAIN  <input type='text' id='currencyVal' value=''><a href='#' id='currencyBtn'>copy</a>

COPY1 <input type='text' class='currencyCopy' value=''>
COPY2 <input type='text' class='currencyCopy' value=''>
COPY3 <input type='text' class='currencyCopy' value=''>
COPY4 <input type='text' class='currencyCopy' value=''>

Fiddle example

Upvotes: 1

Views: 2472

Answers (2)

Kevin
Kevin

Reputation: 41885

You got the wrong selector:

$("a#currencyBtn").click(function(){ // target the anchor with an ID of `#currencyBtn`
  // #currentBtn a | not an element with an ID of `#currencyBtn` with a child anchor
  var value = $('#currencyVal');
  var input = $('.currencyCopy');
  // value.val() // get the value first
  input.val(value.val());
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
MAIN  <input type='text' id='currencyVal' value=''>
<a href='#' id='currencyBtn'>copy</a><br>
<br>
COPY1 <input type='text' class='currencyCopy' value=''><br>
COPY2 <input type='text' class='currencyCopy' value=''><br>
COPY3 <input type='text' class='currencyCopy' value=''><br>
COPY4 <input type='text' class='currencyCopy' value=''><br>

Upvotes: 1

Sam
Sam

Reputation: 2917

Try this

$("a#currencyBtn").click(function(){
        var value = $('#currencyVal').val();
        var input = $('.currencyCopy');
        input.val(value);
    });

Upvotes: 0

Related Questions