代码之家  ›  专栏  ›  技术社区  ›  Muiter

getElementById检查是否包含维度[closed]

  •  -4
  • Muiter  · 技术社区  · 6 年前

    有几种方法可以检查表单字段,如

    document.getElementById('xx['+nr+']').value.length != ''
    document.getElementById('xx['+nr+']').value.length != ''
    document.getElementById('xx['+nr+']').value.length > 5
    

    但是如何检查表单中的textfield是否包含 3512x525x88 ?

    numbers x numbers x numbers ?

    2 回复  |  直到 6 年前
        1
  •  1
  •   rmn    6 年前

    使用regex检查 图案。所以,假设您将文本字段中的值放入一个名为 input

    /^\d+x\d+x\d+$/i.test(input)
    
        2
  •  1
  •   Thijs    6 年前

    可以使用正则表达式来匹配项的值。

    const
      // This regex will match a text which:
      // - starts with one or more digits
      // - followed by an 'x'
      // - followed by one or more digits
      // - followed by an 'x'
      // - followed by one or more digits
      regexDimension = /^\d+x\d+x\d+$/;
      
    // Get the elements from the DOM which may contain a dimension and iterate
    // over all those elements.
    document.querySelectorAll('.item').forEach(item => {
      // Check if the value of the element matches the regex.
      if (regexDimension.test(item.value.trim())) {
        // Do something with the element.
        item.style.backgroundColor = 'lightgreen';
        console.log(`Dimension found: ${item.value} (id=${item.id})`);
      }
    });
    <input class="item" type="text" value="1" id="not-me">
    <input class="item" type="text" value="1x2" id="not-me-either">
    <input class="item" type="text" value="1x2x3" id="pick-me">
    <input class="item" type="text" value="3512x525x88" id="or-pick-me">