【问题标题】:Transparently read from a form element, whose type is irrelevant, with jquery使用jquery从类型无关的表单元素中透明地读取
【发布时间】:2011-10-05 23:49:42
【问题描述】:

我想要这样的功能

// get the value of a form element the way it would be submitted
// by the form
function getVal(fieldName) {
  var $field = $(':input[name=' + fieldName + ']');

  // radio buttons
  if ($field.is(':radio')) {
    return $(':input[name=' + fieldName + ']:checked').val();
  }

  // textarea, input[type=text], select
  else {
    return $field.val();
  }
}

上面的工作很好,因为它处理单选按钮和其他类型的表单输入(不是复选框,但我暂时不关心)。

我想知道 jquery 是否还没有我应该使用的内置函数或选择器?因为对我来说,单选按钮在功能上与选择完全相同(单选)。我不明白为什么我应该区别对待

【问题讨论】:

    标签: jquery forms input radio-button


    【解决方案1】:

    很多人都会同意val() 应该采用这种方式(基于有关获取单选按钮值的问题数量)。

    这很奇怪,因为:

    1. val() already acts intelligently for <select> elements.

    2. val() sets radio buttons intelligently.
      例如,给定:

      <input type="radio"  name="r" value="radio1"/> rad1 txt
      <input type="radio"  name="r" value="radio2"/> rad2 txt
      

      然后:

      $("input[name='r']").val(["radio2"]);
      

      检查正确的按钮!


    那么为什么val() 读取 单选按钮不能智能呢?显然,因为它就是这样开始的,并且担心破坏旧代码。 (虽然我不知道是否有人在单个单选按钮节点上使用 val() 来读取其未选中的值——或者为什么有人想要这样做。)

    加入the discussion on the jQuery dev forum

    【讨论】:

    • 感谢指点!所以目前没有办法统一访问值,甚至没有使用一些 :checkedIfCheckedIsApplicable 选择器......
    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    • 2013-04-20
    • 2010-11-02
    • 1970-01-01
    • 2012-08-23
    • 2015-12-04
    相关资源
    最近更新 更多