【问题标题】:How to find all inputs with values如何找到所有带值的输入
【发布时间】:2019-08-09 08:24:30
【问题描述】:

目标是列出页面上所有输入的所有值,但不列出没有值的输入,两个问题:

$(":input").not("[id*=a_prefix_]").map(function() 
    { 
        var value = this.val(); 
        if( value ) console.log(this.id + ":=" + value ); 
    }
);
  1. this.val() 存在问题,我收到错误“对象不支持属性或方法 'val'”,解决方案是什么?
  2. 如何将检查是否有值移动到实际选择中,以便地图仅获取带有值的输入?

【问题讨论】:

  • this.value$(this).val()。并使用each() 而不是map(),因为它看起来不像您在尝试翻译任何内容。

标签: javascript jquery jquery-selectors


【解决方案1】:
var valueArray = $(":input")
    // filter these things out, whatever they are
    .not("[id*=a_prefix_]")
    // filter only the elements that have a value
    .filter(function(){ return this.value.trim(); })
    // map the values
    .map(function(){ return {[this.id]: this.value}; })
    // turn the results into a real array, not a jQuery object of the values
    .get();

【讨论】:

  • 所以我了解过滤器,我唯一的问题是关于 map/get(),看起来您正在返回一个值数组,但我需要返回如下所示的内容:id := value,我是否只需更改地图以返回 this.id + ":=" + this.value?
  • @aphotographer 更新了答案以返回一个以 id 为键的对象
猜你喜欢
  • 2021-01-31
  • 2016-01-31
  • 1970-01-01
  • 2012-12-29
  • 2022-01-16
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多