Reputation:
I'm trying to select the row in a table which contains one
td
with a specific text using the jQuery .filter()
function. My function looks like this....
function getBudgetRowByType(serviceTypeNum) {
alert(serviceTypeNum);
if (parseInt(serviceTypeNum) == 1) {
var row = $('.bgTablePopUp > tbody > tr').filter(function () {
$(this).children("td:contains('Instruction')");
});
return row;
} else if (parseInt(serviceTypeNum) == 2) {
var row = $('.bgTablePopUp > tbody > tr').filter(function () {
$(this).children("td:contains('Research')");
});
return row;
} else if (parseInt(serviceTypeNum) == 3) {
var row = $('.bgTablePopUp > tbody > tr').filter(function () {
$(this).children("td:contains('Administration')");
});
return row;
} else {
// Else nada
return null;
}
}
the html would look something like this...
<table>
<tr>
<td>Instruction</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>Research</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>Administration</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>
I keep getting an undefined result and I'm not sure why...
Upvotes: 2
Views: 2046
Reputation: 23492
Here is a POJS way of doing it (IE9+), otherwise requires Array.prototype.filter
support (for which there are shims for), document.querySelectorsAll
(but you could use other DOM methods to get the tr
elements, or again their are shims available, you can event use jquery to select them) and Node.textContent
(again shims are available, or just walk the DOM and collect the text nodes). I think it is good to see alternatives, and you have already selected an answer for your jQuery.filter
issue. You may also find the use of a switch
statement better for what you are doing.
Javascript
function contains(elements, string) {
return Array.prototype.filter.call(elements, function (tr) {
return tr.textContent.indexOf(string) !== -1;
});
}
function getBudgetRowByType(serviceTypeNum) {
var row = null,
selector = "table tr";
switch (parseInt(serviceTypeNum)) {
case 1:
row = contains(document.querySelectorAll(selector), "Instruction");
break;
case 2:
row = contains(document.querySelectorAll(selector), "Research");
break;
case 3:
row = contains(document.querySelectorAll(selector), "Administration");
break;
default:
}
return row;
}
console.log(getBudgetRowByType("1"));
console.log(getBudgetRowByType("2"));
console.log(getBudgetRowByType("3"));
console.log(getBudgetRowByType("4"));
On jsfiddle
Upvotes: 0
Reputation: 44740
use .filter
like this - (same for other conditions)
if (parseInt(serviceTypeNum) == 1) {
var row = $('.bgTablePopUp > tbody > tr > td').filter(function () {
return $.trim($(this).text()) === "Instruction";
}).closest('tr');
return row;
}
Upvotes: 2