javascriptdomcypress

How to check that at least one input in a group has a value


I have some inputs in the following div

cy.get("div[data-test-letterinputcontainer='0']")

One of them have a value, but it is not known which. It could for example look like this

<div data-test-letterinputcontainer="0">
    <input value="" type="text">
    <input value="" type="text">
    <input value="f" type="text">
    <input value="" type="text">
    <input value="" type="text">
    <input value="" type="text">
</div>

or this

<div data-test-letterinputcontainer="0">
    <input value="g" type="text">
    <input value="" type="text">
    <input value="" type="text">
    <input value="" type="text">
    <input value="" type="text">
    <input value="" type="text">
</div>

How can I check that


Solution

  • This should do the trick

    cy.get("div[data-test-letterinputcontainer='0'] input")
      .then(($ele) => {
        let flag = false;
        for (let i = 0; i < $ele.length; i++) {
          if (Cypress.$($ele[i]).val().toString().length) {
            //in case we found another input with a value.
            if (flag) {
              return false;
            }
            //first time finding a value for input.
            flag = true;
          }
        }
        return flag;
      })
      .should('eq', true);