【问题标题】:How to change the "value" and "id" of a button based on the selection of a separate set of radio buttons如何根据选择一组单独的单选按钮来更改按钮的“值”和“id”
【发布时间】:2012-07-08 05:35:45
【问题描述】:

我有一个包含两个单选按钮和一个按钮的表单。我想根据选择的两个单选按钮中的哪一个来更改按钮的值。我的猜测是使用 jQuery 比使用 PHP 更好,但如果这是错误的假设,请告诉我。

这是一个 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>

简而言之,我想用选中的单选按钮的值替换按钮 id 和值。因此,如果选择了第二个单选按钮,按钮标签将如下所示:

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

【问题讨论】:

  • 为什么?单选按钮的值会被提交,为什么要复制到按钮上呢?
  • 请问为什么不使用提交单选按钮的值?
  • 我这样做是因为单选按钮和按钮将在后续页面上使用,并且这些按钮已预先选择。上面的 HTML 代表三列之一。当用户选择基本 1 的单选按钮,然后单击确认时,我希望在下一页上预先选择基本 1 单选按钮和确认按钮。然后,用户将在后续表格中填写其他信息。我从上面的两个 cmets 中得知我正在努力做到这一点。

标签: jquery forms button radio-button


【解决方案1】:

你可以这样做:

$(':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

但选中的radio 值将自动提交。

【讨论】:

    【解决方案2】:

    只需更改控件的名称,它就会发送与更改按钮值相同的表单数据:

    <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>
    

    【讨论】:

      【解决方案3】:
      $('input:radio').click(function(){
        $('button').prop({'id' : $(this).val(), 'value' : $(this).val()});   
      });
      

      【讨论】:

        猜你喜欢
        • 2015-01-22
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 2018-06-03
        • 1970-01-01
        相关资源
        最近更新 更多