最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting a radio button ID with jQuery - Stack Overflow

programmeradmin1浏览0评论
$(function () {
    $("#MyInputBox").keyup(function () {
        var nextChk = $(this).next(":radio:checked").attr('id'));
        alert(nextChk);
    });
});

What is the correct way to say "Get the ID of the next checkbox which is checked" Am I even close?

$(function () {
    $("#MyInputBox").keyup(function () {
        var nextChk = $(this).next(":radio:checked").attr('id'));
        alert(nextChk);
    });
});

What is the correct way to say "Get the ID of the next checkbox which is checked" Am I even close?

Share Improve this question edited Jan 10, 2012 at 14:26 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jan 10, 2012 at 14:19 JustAnotherDeveloperJustAnotherDeveloper 3,19911 gold badges40 silver badges70 bronze badges 3
  • You're asking about DOM traversal, but you're not providing your DOM. – user1106925 Commented Jan 10, 2012 at 14:23
  • @amnotiam : Didn't bother providing a DOM as it's a generic question :) Should have mentioned the assumption I suppose. – JustAnotherDeveloper Commented Jan 10, 2012 at 14:28
  • @RawryLions: Well, no DOM traversal question is generic. Some people try to use .next() when the elements aren't actually siblings (like when they're nested in ancestors that are siblings). So it always depends on the actual markup. – user1106925 Commented Jan 10, 2012 at 14:29
Add a ment  | 

1 Answer 1

Reset to default 6

Assuming your radio inputs are all siblings, you'd need to use .nextAll(), and then narrow down to the first match.

$(this).nextAll(":radio:checked:first").attr('id');

or

$(this).nextAll(":radio:checked").first().attr('id');

Or you could technically use .nextUntil() with .next().

$(this).nextUntil(":radio:checked").next().attr('id');

Also, I see that you're asking about checkboxes, but your code uses :radio, so I guess I don't know which one you actually want.

发布评论

评论列表(0)

  1. 暂无评论