0

I am trying to use jQuery to detect if a table row has one or two inputs...

<tr class="myoptions">
    <td class="label">
        <label>
            <strong>Options</strong>
        </label>
    </td>
    <td class="value">
        <div>
            <input type="radio" value="test1">
            <label>
                test1
            </label>
        </div>
        <div>
            <input type="radio" value="test1">
            <label>
                test1
            </label>
        </div>
    </td>
</tr>

How can I count the inputs inside this tr? Does anybody have an example I can see?

1
  • 1
    $(".value input").length ? Commented Jan 24, 2018 at 22:15

2 Answers 2

1
var numberOfInputs = $(".myoptions").find("input").length

var numberOfInputs = $(".myoptions").find("input").length;

console.log(numberOfInputs);

if (numberOfInputs < 1) {
  console.log("No input");
} else if (numberOfInputs === 1) {
  console.log("One input");
} else if (numberOfInputs === 2) {
  console.log("Two inputs");
} else {
  console.log("More than two inputs");
}
<table>
  <tr class="myoptions">
    <td class="label">
      <label>
            <strong>Options</strong>
        </label>
    </td>
    <td class="value">
      <div>
        <input type="radio" value="test1">
        <label>
                test1
            </label>
      </div>
      <div>
        <input type="radio" value="test1">
        <label>
                test1
            </label>
      </div>
    </td>
  </tr>
</table>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

One important thing to notice is that you absolutely need a <table> element parent since you use <tr>, otherwise the browser will wipe out your <tr> elements from the DOM - making them unreachable.

Sign up to request clarification or add additional context in comments.

Comments

0

Lookup for the inputs in the row class .value... Which is a strange class name, by the way. Can be confusing...

Then .length property will tell you how many there is in the collection.

console.log( $(".value input").length );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr class="myoptions">
    <td class="label">
        <label>
            <strong>Options</strong>
        </label>
    </td>
    <td class="value">
        <div>
            <input type="radio" value="test1">
            <label>
                test1
            </label>
        </div>
        <div>
            <input type="radio" value="test1">
            <label>
                test1
            </label>
        </div>
    </td>
  </tr>
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.