如何获取 Jquery 中复选框的值

How to get the value of checkbox in Jquery

我有一个 HTML 元素:

<a style='text-decoration:none;' id='$innerdata[0]' class='cat' href='#'>    <input type='checkbox' name='vehicle' value='Bike'> $innerdata[1]</a>

我正在尝试获取复选框的值,但是 alert() 正在打印未定义。

$('body').on('click', '.cat', function() 
{
    $topcat = $(this);
    alert ($topcat.closest().find('[type=checkbox]').val());
}

如何获取复选框的值?

省略 closest - 您只需要 find

$topcat.find(':checkbox').val();
$('input[type=checkbox][name=vehicle]').val()     // general method using jQuery

您应该添加一些独特的 idclass,否则选择正确的输入可能会很棘手。参见:

// Selects first checkbox with name `asd`
$('input[type=checkbox][name=asd]:eq(0)').val()   // jQuery
$('input[type=checkbox][name=asd]')[0].value      // jQuery + DOM