Search code examples
jqueryradio-buttontextinput

How do I add values from radio and input text to another input text when selected?


I have a radio list to pick a payment value. When you choose the payment value it adds to the amount text input.

I also have an option for 'other amount'.

What I would like to do is click 'other amount', show a hidden text input, when you add a value, it adds to the 'amount text input'.

If you then click back on one of the other radio values it hides the 'other-amount' text input and the value is changed to whichever selection was made.

HTML:

<div id="donation">
    <input type="radio" name="my-input" id="0" value="$10.00" />
    $10.00<br />
    <input type="radio" name="my-input" id="1" value="$25.00" />
    $25.00<br />
    <input type="radio" name="my-input" id="2" value="$50.00" />
    $50.00<br />
    <input type="radio" name="my-input" id="3" value="$2500.00" />
    $2500.00<br />
    <input type="radio" name="my-input" id="other" value="Other Amount" />
    Other Amount
</div>

<input type="text" id="other-amount" name="other-amount" />

<input type="text" id="amount" name="amount" readonly="readonly" />

Javascript so far:

$(document).ready(function() {

$("#donation input[type=radio]").filter(function() {
    return $(this).val() == $("#amount").val();
}).attr('checked', true);

$("#donation").live("change", function() {

    $("#amount").val($(this).find("input[type=radio]:checked").attr("value"));
});
});

Solution

  • To copy the value from one text box to another you can this

     $('#other-amount').on('keyup', function(){
              $("#amount").val($(this).val());     
      });
    

    To hide it on any other radio select

     $('input:radio[id!=other]').on('click', function(){
        $('#other-amount').hide();
    });
    

    See a working example here