根据输入焦点检查单选按钮

时间:2017-11-29 19:28:14

标签: jquery html

当用户点击输入字段时,我正在尝试检查单选按钮。我无法弄清楚如何识别单选按钮。以下代码什么都不做......

 $(function() {
   $('.searchInput').focus(function() {
     $(this).prev('.radio').find(':radio').prop('checked', true);

   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align='left' width='100%' class='searchWindow'>
  <tr>
    <td>
      <input type='radio' class='radio' name='searchType' value='byUser'>
      <th>By User</th>
      <td colspan='2'>
        <input type='text' id='user' size='32' class='searchInput'>
      </td>
  </tr>
  <tr>
    <td>
      <input type='radio' class='radio' name='searchType' value='byDate'>
      <th width='20%'>By Date</th>
      <td width='35%'>
        <input type='text' id='beg' size='8' placeholder='Begin Date' class='searchInput'>
      </td>
      <td width='35%'>
        <input type='text' id='end' size='8' placeholder='End Date' class='searchInput'>
      </td>
  </tr>

  <tr>
    <td>
      <input type='radio' id='ff' name='searchType' class='radio' value='bySubject'>
      <th>By Subject</th>
      <td colspan='2'>
        <input type='text' id='subject' size='32' class='searchInput'>
      </td>
  </tr>
</table>

2 个答案:

答案 0 :(得分:1)

您使用的方法不对。使用closest('tr')查找祖先tr,然后find(':radio')查找其中的radio按钮。

$(this).closest('tr').find(':radio').prop('checked', true);

答案 1 :(得分:0)

DOM导航是关键。

如果输入 - 在这种情况下是tr行,你需要考虑一对的“公共容器”。

然后,一旦识别出公共容器,就可以find进行所需的输入。

最好使用closest查找最近的tr祖先,然后find

这看起来像这样:

$(this).closest('tr').find('input.radio').prop('checked', true);
相关问题