JavaScript map(function) return this.value - 找到数组中的最后一个元素

时间:2021-07-16 08:19:14

标签: javascript html

按照上一个查询:

Javascript - map(function) return this.value - comma on wrong side

我有我想区分的元素之一。 也就是说,我想要这个对象后面的“-”元素。

我在这里找到了一些解决方案:

Javascript Map Array Last Item

并试图摆弄我的代码,不幸的是没有奏效。

HTML:

      <fieldset id="ophealth_safety">
      <div>
      <input type="checkbox" id="opladdert" name="health_safety" value="Triple ladders">
      <label class="checking" for="opladder">Triple Ladders</label>
      </div>
      <div>
      <input type="checkbox" id="opgardens" name="health_safety" value="Access private gardens required">
      <label class="checking" for="opgardens">Access private gardens required</label>
      </div>
      <div>
      <input type="checkbox" id="opskylight" name="health_safety" value="Skylight">
      <label class="checking" for="opskylight">Skylight</label>
      </div>
      <div>
      <input type="checkbox" id="oploft" name="health_safety" value="Access Loft">
      <label class="checking" for="oploft">Access Loft</label>
      </div>
      <div>
      <input type="checkbox" id="oproof" name="health_safety" value="Access to roof">
      <label class="checking" for="oproof">Access to roof</label>
      </div>
      <div>
      <input type="checkbox" id="opother" name="health_safety" value="Other">
                                                <label class="checking" for="opother">Other</label>
                                                <input type="text" id="opotherdesc" name="other" pattern="[A-Za-z].{4,}" title="The text should include at least 4 letters" placeholder="Please specify">
                                            </div>
                                        </fieldset>

JAVASCRIPT:

    var healthSafety = $('input:checkbox[name=health_safety]:checked').map(function() {
    const lastIndex = row.length - 1;
    row.map((rank, i) => {
        if (i === lastIndex) {
            .join(" - ")
        } else {
            return this.value;
            }).get().join(", ")
    });

我目前:

健康与安全:需要进入私人花园,进入阁楼,其他天花板

我想要这样的东西:

健康与安全:需要进入私人花园,进入阁楼,其他 - 天花板

我的代码中缺少什么?

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确解决了您的问题,但我会尽力提供帮助。

您要解决的第一个问题是获取以逗号分隔的复选框值列表,可能是这样的:

const selector = 'input[name="health_safety"]:checked';
const values = Object.values(document.querySelectorAll(selector)).map(input => input.value);

既然您有了列表,您想检查列表中是否有“其他”(最后一个元素)可用。如果是,则要附加“-”,后跟文本输入的值:

let healthSafety = values.join(', ') + (
    values[values.length - 1] === 'Other' 
        ? ' - ' + document.getElementById('opotherdesc').value 
        : ''
);

https://jsfiddle.net/afe8otzn/3/

相关问题