Reputation: 12568
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?
Upvotes: 0
Views: 1227
Reputation: 206007
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.
Upvotes: 1
Reputation: 33933
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>
Upvotes: 0