选择最近的无线电输入

时间:2014-11-23 13:55:23

标签: jquery

我喜欢以下

 <input type="radio" name="day_time[]" class="pickup-location-day" value="Sunday"> Sunday
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:00am"> 02:00am
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:30am"> 02:30am
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="05:30am"> 05:30am<br>

  <input type="radio" name="day_time[]" class="pickup-location-day" value="Sunday"> Monday
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:00am"> 02:00am
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:30am"> 02:30am
 <input type="radio" name="pickup_time[]" class="pickup-location-time" value="05:30am"> 05:30am<br>

 etc .... 

我希望在选择.pickup-location-time时使用第一个.pickup-location-day进行绑定,例如当用户选择最近的.pickup-location-time&#39; .pickup-location-day&#39;也应该选择。

请注意,我使用了以下

$('.pickup-location-time').on('change', function() {
   $(this).closest('.pickup-location-time').prop('checked', true);
})

但这无济于事

enter image description here

3 个答案:

答案 0 :(得分:3)

将您的无线电包装成组,以便您可以在特定组内进行遍历。这简化了隔离实例

<div class="radio-group">
    <input type="radio" name="day_time[]" class="pickup-location-day" value="Sunday">Sunday
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:00am">02:00am
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:30am">02:30am
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="05:30am">05:30am       
</div>
<div class="radio-group">
    <input type="radio" name="day_time[]" class="pickup-location-day" value="Sunday">Monday
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:00am">02:00am
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="02:30am">02:30am
    <input type="radio" name="pickup_time[]" class="pickup-location-time" value="05:30am">05:30am       
</div>

然后你可以这样做:

$('.pickup-location-time').on('change', function () {
    $(this).parent().find('.pickup-location-day').prop('checked', true);
})

DEMO

答案 1 :(得分:0)

使用prev()

$(this).prev('.pickup-location-day').prop('checked', true);

请务必选择.pickup-location-day

答案 2 :(得分:0)

你是对的,.closest()做了一些完全不同的事情。

如果您控制文档结构,为什么不使用$(this).next('.pickup-location-time'),因为它始终是您要选择的下一个元素?