【问题标题】:Set the value of a radio button to the value of an other input field in Jquery将单选按钮的值设置为 Jquery 中其他输入字段的值
【发布时间】:2011-10-24 02:01:31
【问题描述】:

我有几组单选按钮,其中最后一组是“其他”字段,用户可以在其中指定他们的“其他”答案。

我想将“其他”单选按钮的值设置为刚刚填写的“其他”文本输入字段的值。

这是我的html:

<fieldset>
    <h3>We are online via ...</h3>
    <label for="online_via[1]">
        <input type="radio" name="online_via" id="online_via[1]" value="laptop" /> Laptop
    </label>
    <label for="online_via[2]">
        <input type="radio" name="online_via" id="online_via[2]" value="desktop" /> Desktop
    </label>
    <label for="online_via[3]">
        <input type="radio" name="online_via" id="online_via[3]" value="mobile" /> GSM, Smartphone, PDA
    </label>
    <label for="online_via[4]">
        <input type="radio" name="online_via" id="online_via[4]" alue="tablet" /> Tablet
    </label>
    <label for="online_via[other]">
        <input type="radio" name="online_via" id="online_via[other]" value="other" /> Other, specify: <input type="text" id="online_via[specified]" class="other" />
    </label>
</fieldset>

如您所见,最后一个单选按钮在其标签标记中包含一个 input[type="text"]。我想取它的值,并将其用作另一个单选按钮的值。 这是我在 Jquery 中一直在尝试的:

$(function(){
    $('.other').keyup(function(){
      var radio = $(this).attr('id').replace('specified','other');
      $('input#' + radio).attr("value", $(this).val());
      console.log($('input#' + radio).val());
    });
});

我不断得到“未定义”。我究竟做错了什么? Jquery jedis 联合起来!

P.S.:请记住,我有几组单选按钮。 PPS:#online_via[specified] 字段没有 name 属性的原因是因为我想在发布数据时忽略它,因为我希望将其值存储在 #online_via[other] 字段中。

期待您的回复。

【问题讨论】:

    标签: jquery button input set radio


    【解决方案1】:
    $(function(){
        $('.other').keyup(function(){
          $(this).parent().find('input[type=radio]').val($(this).val());
        });
    });
    

    这对你有用吗?

    【讨论】:

    • 哇!一个真正的 jquery 绝地武士,你就是!我接受你的回答,但 SO 告诉我等 10 分钟。
    • 只是为了澄清为什么您的代码不起作用,这是因为 jQuery 在选择中使用[]。它在上面的代码中使用,用于搜索其属性的某些内容,因此使用您的代码 jQuery 正在搜索具有 other 属性的#id。所以你应该只在 id 和 classes 中使用字母数字。
    【解决方案2】:

    先这样做:

    <label for="online_via[other]">
            <input type="radio" class="otherClass" name="online_via" id="online_via[other]" value="other" /> Other, specify: <input type="text" id="online_via[specified]" class="other" />
        </label>
    

    然后:

    $('.other').keyup(function(){
    
          $('.otherClass').val($(this).val());
          console.log($('.otherClass').val());
        });
    

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多