Ken
Ken

Reputation: 3141

How to change the "value" and "id" of a button based on the selection of a separate set of radio buttons

I have a form that includes two radio buttons and a button. I would like to change the value of the button based on which of the two radio buttons is selected. My guess is that it's better to use jQuery than PHP for this, but please let me know if that's the wrong assumption.

Here's an example of the HTML:

<form>
  <ul>
    <li>
     <input type="radio" name="basic" value="basic1">
     <label for="basic1">Basic 1</label>
    </li>
    <li>
    <input type="radio" name="basic" value="basic2">
    <label for="basic2">Basic 2</label>
    </li>
  </ul>
  <button id="basic1" name="startReg" type="submit" value="basic1">Confirm</button>
</form>

In short, I want to replace the button id and value with the value of whichever radio button is selected. So, if the second radio button is selected, the button tag will look like this:

<button id="basic2" name="startReg" type="submit" value="basic2">Confirm</button>

Upvotes: 2

Views: 765

Answers (3)

Guffa
Guffa

Reputation: 700192

Just change the names of the controls, and it will send the same form data as it would if you change the value of the button:

<form>
  <ul>
    <li>
     <input type="radio" name="startReg" value="basic1" checked="checked">
     <label for="basic1">Basic 1</label>
    </li>
    <li>
    <input type="radio" name="startReg" value="basic2">
    <label for="basic2">Basic 2</label>
    </li>
  </ul>
  <button id="basic1" name="somethingElse" type="submit">Confirm</button>
</form>

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

You can do this:

$(':radio').on('change', function() {

  // this.value for get the id of radio

  $('button[name=startReg]')
                        .attr('id', this.value )   // change id of button
                        .val( this.value );        // update value of button
});

DEMO

but selected radio value will auto submit.

Upvotes: 3

Ohgodwhy
Ohgodwhy

Reputation: 50767

$('input:radio').click(function(){
  $('button').prop({'id' : $(this).val(), 'value' : $(this).val()});   
});

Upvotes: 1

Related Questions