如何获取动态生成名称的单选按钮的值

3

我有一堆动态生成名称的单选按钮,如下所示:

        <input type="radio" id="Red<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Red" <?php if ($category == "Red") { ?>checked="true"<?php } ?>>
          <label for="Red<?php echo $wineID; ?>">Red</label>

        <input type="radio" id="White<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="White" <?php if ($category == "White") { ?>checked="true"<?php } ?>>
          <label for="White<?php echo $wineID; ?>">White</label>

        <input type="radio" id="Sparkling<?php echo $wineID; ?>" name="category<?php echo $wineID; ?>" value="Sparkling" <?php if ($category == "Sparkling") { ?>checked="true"<?php } ?>>
          <label for="Sparkling<?php echo $wineID; ?>">Sparkling</label>

我需要获取选中的值,并将其添加到我的dataString中,以便使用jQuery进行ajax调用更新数据库。如何实现这一点?

4个回答

3

试试这个:

$('input[type="radio"]:checked')

比如:

alert( $('input[type="radio"]:checked').val() );

1
你可以使用属性选择器来获取元素。
$('input[name="category<?php echo $wineID; ?>:selected"')

然而这个方法使用了PHP内联脚本,所以只有在页面加载时才能起作用。
或者最简单的方法是:
console.log($(":radio:selected").val());

1
您可以通过 onchange 事件(使用 jQuery)获取 name 属性。
// Onload handler
$(function() {
    // Get all radio buttons and add an onchange event
    $("input[type=radio]").on("change", function(){
        // Output a message in the console which shows the name and state
        console.log($(this).attr("name"), $(this).is(":checked"));

    // Trigger the onchange event for any checked radio buttons after the onload event has fired
    }).filter(":checked").trigger("change");
});

0

你可以使用一个具有id="anything"的父级div。

现在使用jQuery选择器$('#anything input[type="radio"]:checked').val()

你可以实现这个功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接