JQUERY Change TD style ONLY IF IT contains input type = text (and not input type=radio)

走远了吗. 提交于 2019-12-11 04:24:28

问题


I have applied a style as follows and it works great for me:

$("td[id='cellId']").css("text-align", "left");

However, I need that style to only be applied to the TD IF it contains textboxes and NOT radio buttons.

I have searched hi and low, but find(), contains() and the likes, does not seem to be working.


回答1:


If you need to filter TD-s which contain textboxes and NOT radio buttons, then you need to use :has and :not combination:

 $("td:not(:has(input[type='radio']))").has("input[type='text']").css("background", "red");

Here is a snippet where filtered cells got a red background. You can apply any style to them.

$("td:not(:has(input[type='radio']))").has("input[type='text']").css("background", "red");
td {
    border: 1px solid green;
    padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
 <tr>
  <td><input type="text">cell-1-1</td>
  <td><input type="radio">cell-1-2</td>
  <td><input type="text"><input type="radio">cell-1-3</td>
 </tr>
 <tr>
  <td><input type="radio">cell-2-1</td>
  <td><input type="text">cell-2-2</td>
  <td>cell-2-3</td>
 </tr>
</table>



回答2:


Use the :has() selector to match elements that contain other elements.

$("td#cellId:has(:text)").css("text-align", "left");



回答3:


First note that your $("td[id='cellId']") is rather surprising: I may guess that you have some var cellId which contains the cell id, so you should use $('#' + cellId).

Now, since you didn't precise about the (eventually) nested elements in the td, we must ensure there is no radio button inside it.
Anyway let's suppose we have var cellElem that you've populated as needed (may be like showed above).

So you may use something like this:

if (!cellElem.find([type=radio]).length) {
    cellElemn.css(textAlign: 'left');
}


来源:https://stackoverflow.com/questions/41309298/jquery-change-td-style-only-if-it-contains-input-type-text-and-not-input-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!