使用 jquery 将选中的无线电附加到表单中

Append radio checked to the form using jquery

本文关键字:表单 无线电 jquery 使用      更新时间:2023-09-26

im在一个小应用程序上工作,但我无法解决这个问题我试图使用jQuery将检查过的无线电附加到表单中,我确实尝试了很多解决方案,但我确实失败了我在这里写了代码,希望有人可以帮助我解决这个问题

<div class="radio">
    <label>
        <input type="radio" name="optionsRadios" id="optionsRadios" value="interior">
        Interior
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio" name="optionsRadios" id="optionsRadios" value="exterior">
        Exterior
    </label>
</div>
<div class="radio">
    <label>
        <input type="radio" name="optionsRadios" id="optionsRadios" value="interio+exterior">
        Interior si exterior
    </label>
</div>

这里的数据是使用 json 获取的,我有正确的结果

 <script>
        $.each(data, function (k, v) {
                        typdespal = v.typdespal;
                        // the problem is that always i cant get the radio checked in the right position from the database
                       // $('#optionsRadios').val(typdespal);
                        $("input:radio[name='optionsRadios']").val(typdespal).prop( "checked", true );;
        </script>
您可以使用

filter()找到带有值的正确单选按钮,然后将其属性设置为选中。

$("input:radio[name='optionsRadios']").filter(function(){
   return $(this).val() === typdespal
}).prop( "checked", true);

首先,您需要将所有内容包装在 Document.Ready 调用中。然后,您只需将选中的功能应用于包含适当值的复选框。目前,您正在设置所有optionsRadios的值。您可以使用prop函数重载来执行此操作:

$(function() { // DOM ready
    $("input:radio[name='optionsRadios']").prop("checked", function() {
       // Only set the checked value when this checkbox value === the corresponding data value
       var val = $(this).val();
       return val === data[val].typdespal;
    });
});

注意:我认为我正在正确读取您的数据对象,如果不看到它就很难分辨:)

首先,多个单选按钮可能具有相同的名称,但不是 ID。所以让他们独一无二。其次,尝试将选择器更改为:

 $("input:radio[value='"+typdespal+"']").prop( "checked", true );