cdr6800
cdr6800

Reputation: 105

Change value of textbox based on radio box selection

I am trying to change the value of a textbox based on the selection a group of 4 radio buttons. This is not the actual html code, but a simplified version:

    <input type="radio" name="radiogroup" id="radiogroup" value="5" />
    <input type="radio" name="radiogroup" id="radiogroup" value="10" />
    <input type="radio" name="radiogroup" id="radiogroup" value="15" />
    <input type="radio" name="radiogroup" id="radiogroup" value="20" />

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

So what I am trying to do is fill the textbox named "amount" with either 5, 10, 15 or 20 based on which radio button is selected.

I am new to jquery and everything I tried did not work.

Thank you in advance for any help.

cdr6545

Upvotes: 3

Views: 6156

Answers (3)

adeneo
adeneo

Reputation: 318342

ID's are unique, and an ID can only be used on one element in the current document, so change it to classes.

Then attach a change event handler to the radios, get the checked one, and set the value of the text input to the checked radios value

$('.radiogroup').on('change', function() {
  $('#amount').val( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="radiogroup" class="radiogroup" value="5" />
<input type="radio" name="radiogroup" class="radiogroup" value="10" />
<input type="radio" name="radiogroup" class="radiogroup" value="15" />
<input type="radio" name="radiogroup" class="radiogroup" value="20" />
<br /><br />
<input type="text" name="amount" id="amount" />

Upvotes: 1

Mehmood
Mehmood

Reputation: 931

You can easily do this by adding class.

Working Fiddle

HTML:

    <input type="radio" name="radiogroup" id="radiogroup" class="radiogroup" value="5" />
    <input type="radio" name="radiogroup" id="radiogroup" class="radiogroup" value="10" />
    <input type="radio" name="radiogroup" id="radiogroup" class="radiogroup" value="15" />
    <input type="radio" name="radiogroup" id="radiogroup" class="radiogroup" value="20" />

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

JS:

$('.radiogroup').change(function(e){
    var selectedValue = $(this).val();
    $('#amount').val(selectedValue)
});

Upvotes: 6

MisterDebug
MisterDebug

Reputation: 923

Something like:

$('input[name="radiogroup"]').click(function()
{
    $('#amount').val($(this).val())
})

Upvotes: 0

Related Questions