How to change the value of radio buttons using Javascript/Jquery

15,871

Solution 1

jQuery selector:

$('input[value="2"][name="foo"]')

Solution 2

Use this:

$('[name="foo"]').val(2); 
Share:
15,871
gregory boero.teyssier
Author by

gregory boero.teyssier

https://ali.actor

Updated on June 17, 2022

Comments

  • gregory boero.teyssier
    gregory boero.teyssier almost 2 years

    Say I have this radio:

    <form name="myForm">
      <input type="radio" name="foo" value="1"> 1
      <input type="radio" name="foo" value="2"> 2
    </form>
    

    I'm looking for a way to do something like this:

    document.myForm.foo.value = "2";
    

    In order to dynamically select the 2nd radio button. Or a way to do the following using jquery.

  • gregory boero.teyssier
    gregory boero.teyssier almost 12 years
    Won't work because what if I want to move the radio options around?
  • gregory boero.teyssier
    gregory boero.teyssier almost 12 years
    what if I have more than 1 radios or inputs?
  • gregory boero.teyssier
    gregory boero.teyssier almost 12 years
    What if I have more than one sets of radios who both have values of 2? e.g <input name = foo value = 2 /> and <input name = bar value = 2 /> and I want to only select the foo one
  • j08691
    j08691 almost 12 years
    If you want something that addresses that question it should be part of your original question.
  • Danilo Valente
    Danilo Valente almost 12 years
    it's just a fast example that shows you can select it by his name. So, the better solutiuon is to keep the same name but set different ids, like option1 and option2
  • Elliot Bonneville
    Elliot Bonneville almost 12 years
    @ClickUpvote: Answer updated to match two selectors as per request.