0

Im looking to do something like @JCOC611 did here: https://stackoverflow.com/a/5099898/3223200

In which you can change the TEXT value depending on the RADIO BUTTON selection

Who ever, I would like to have several forms in the same page, how can this be done?

The original code is

<input type="text" id="it" value="">
<input type="radio" name="hey" value="one">
<input type="radio" name="hey" value="two">
<input type="radio" name="hey" value="three">

<script>
$(document).ready(function(){
  $("input[type=radio]").click(function(){
     $("#it").val(this.value);
  }); 
});
</script>

Demo here: http://jsfiddle.net/jcoc611/rhcd2/1/

And I would like something like this:

<form action="hello.php" name="form01" method="post">
<input type="hidden" name="productid" value="01" />
<input type="radio" name="price" value="1000">
<input type="radio" name="price" value="2000">
<input type="text" id="it" name="pricevalue" value="">
</form>

<form action="hello.php" name="form02" method="post">
<input type="hidden" name="productid" value="02" />
<input type="radio" name="price" value="6000">
<input type="radio" name="price" value="2400">
<input type="text" id="it" name="pricevalue" value="">
</form>

<form action="hello.php" name="form03" method="post">
<input type="hidden" name="productid" value="03" />
<input type="radio" name="price" value="500">
<input type="radio" name="price" value="700">
<input type="text" id="it" name="pricevalue" value="">
</form>

<script>
$(document).ready(function(){
  $("input[type=radio]").click(function(){
     $("#it").val(this.value);
  }); 
});
</script>

Using multiple forms in the same page, but to use the same function

How can this be done?

1
  • You should not have multiple elements in the DOM with same id. Commented May 9, 2014 at 21:00

2 Answers 2

2

Use:

$(document).ready(function () {
    $("input[type=radio]").click(function () {
        $(this).closest('form').find("input[type=text]").val(this.value);
    });
});

jsFiddle example

By using .closest() and .find() you can pick the text input element closest to the relative radio button selected.

Note that IDs must be unique.

Sign up to request clarification or add additional context in comments.

Comments

0

A bit less code if you use siblings().

$(document).ready(function(){
    $("input[type=radio]").click(function(){
       $(this).siblings("input[type=text]").val(this.value);
    }); 
});

jsFiddle example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.