【问题标题】:How to get value of radio button with dynamically generated name如何使用动态生成的名称获取单选按钮的值
【发布时间】:2013-05-25 08:19:25
【问题描述】:

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

        <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 中,以便 ajax 调用来更新我的数据库。如何使用 jQuery 来做到这一点?

【问题讨论】:

    标签: jquery html forms radio-button


    【解决方案1】:

    试试这个:

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

    如:

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

    【讨论】:

      【解决方案2】:

      你可以使用属性选择器来获取元素

      $('input[name="category<?php echo $wineID; ?>:selected"')
      

      然而,这使用了一个 PHP 内联脚本,所以它只有在页面加载时才会起作用。

      或者最简单的方法是:

      console.log($(":radio:selected").val());
      

      【讨论】:

        【解决方案3】:

        您可以从 onchange 事件中获取 name 属性(使用 jQuery)

        // 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");
        });
        

        【讨论】:

          【解决方案4】:

          您可以将父 div 与 id="anything" 一起使用

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

          你可以做到的

          【讨论】:

            猜你喜欢
            • 2015-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-20
            • 2018-06-03
            • 2015-05-08
            • 1970-01-01
            相关资源
            最近更新 更多