同じテーブルのテキスト ボックス フィールドから値を追加して、テーブルを作成しようとしていtfoot
ます。最終的な目標は、行をさらに追加する機能を残しながら、以前に追加された行をインライン編集できるようにすることです。
次のマークアップがあります。
<table>
<thead>
<tr>
<th>Service</th>
<th>Protocol</th>
<th>Source Port</th>
<th>Destination Port</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<td>
<input type="text" data-function="service" value="foo" />
</td>
<td>
<input type="text" data-function="protocol" value="bar" />
</td>
<td>
<input type="text" data-function="sourcePort" value="baz" />
</td>
<td>
<input type="text" data-function="destPort" value="fob" />
</td>
<td>
<button id="addBtn" type="button">Add</button>
</td>
</tr>
</tfoot>
</table>
The below script stores all of the input[type=text]
elements in the tfoot
in an inputs variable. From there I am trying to use .index()
to identify and then retrieve the value of each textbox:
$(document).ready(function () {
$('#addBtn').click(function (e) {
var inputs = $(this).closest('tfoot').find('input[type=text]');
console.log(inputs);
var serviceIndex = inputs.index('[data-function="service"]');
console.log(serviceIndex);
console.log(inputs[serviceIndex].value);
// the remaining indexes all return -1
var protocolIndex = inputs.index('[data-function="protocol"]');
console.log(protocolIndex);
console.log(inputs[protocolIndex].value);
var sourcePortIndex = inputs.index('[data-function="sourcePort"]');
console.log(sourcePortIndex);
console.log(inputs[sourcePortIndex].value);
var destPortIndex = inputs.index('[data-function="destPort"]');
console.log(destPortIndex);
console.log(inputs[destPortIndex].value);
});
});
Unfortunately the selector data-function="X"
selector only works for service. All of the other selectors return -1
indicating that a value was not found. The above code is from this jsFiddle which illustrates the problem. I am not wedded to using index, but cannot use the element's id
as I need a more general solution.
Why does the jQuery .index() method only work for the first element in the collection, when a selector is specified?