Can I use jQuery find() for more than one element type at the same time?
I am using the following function to change the padding in a column on my forms:
function padTitles() {
$('#option-grid #dataTable tr, #topic-grid #dataTable tr')
.each(function () {
var tds = $(this).find('input'),
text = tds.filter('[id^="input_TempRowKey_"]').val(),
tdToPad = tds.filter('[id^="input_Title_"]'),
pad;
if (/\.0$/.test(text)) {
pad = 10;
level = 1;
} else {
pad = 35;
level = 2;
}
tdToPad.css('margin-left', pad);
a = tdToPad.closest('tr');
if (tdToPad.closest('tr').get().className) {
tdToPad.closest('tr').get().className = tdToPad.closest('tr').get().className.replace(/\blevel\-.*?\b/g, 'level-' + level);
} else {
tdToPad.closest('tr').addClass('level-' + level)
}
});
}
It works well for this form HTML:
<td id="title_1" class=" ">
<input type="text" value="Tests" name="item.Title" id="input_Title_1" >
</td>
Now I would also like it to work for the following HTML:
<td id="title_1" class=" ">
<textarea name="item.Title" id="input_Title_1">Tests</textarea>
</td>
Is there a way I can change this function so it works for either an input
or textarea
? I assume the way to do this is to change var tds = $(this).find('input'),
however I am not sure how to change it or even if it's possible to change to "find" either a textarea or an input.
Solution 1:
Use a comma to union multiple queries:
var tds = $(this).find('input, textarea');
You can also use :input
as a selector, but it's not as efficient and may also include some things you'd rather not include.
Solution 2:
You can use .children()
to select the td
s child whatever it is
var tds = $(this).children();
Solution 3:
You cannot add a textarea
with the same id
as another element. Its incorrect. id
values are unique for a single html element within the document.
I would suggest to you class
instead.
<input type="text" value="Tests" class="myclass" name="item.Title" id="input_Title_1" >
<textarea name="item.Title" class="myclass" id="input_Title_2">Tests</textarea>
var tds = $(this).find('.myclass')