【问题标题】:Display radio button checked if json value is match to condition如果 json 值与条件匹配,则显示选中的单选按钮
【发布时间】:2014-02-12 07:28:18
【问题描述】:

我一直在关注 Json 数据

{"1":"2","2":"2"} 这个可以根据条件改变。

我正在尝试实现单选按钮检查 Json 是否包含与单选按钮相同的值。 在 Json 中,第一个值是无线电名称,第二个是需要匹配的值。

 success : function(result){
        //alert(JSON.stringify(result));
        var contact = JSON.parse(result);
        alert("First: " + contact + " Second: " + contact);
        $('input[type=radio][name="' + group[contact[1]] + '"][value="' + contact[1] + '"]').prop('checked', true);


        }

以下是我的html表单

<table width="50%" border="1" align="center" cellpadding="2" cellspacing="1" >




<th><td colspan='2'> <font color='#006699' size='3' face='Arial, Helvetica, sans-serif'><strong>    Assign User Role </br></br></strong></font></td></th>


 <tr bgcolor="#FFFFFF">
    <td><strong>Select User:</strong></td>
    <td><input type="text" name="assigned_to" id="assigned_to" /></td>
 </tr>

<tr bgcolor="#FFFFFF">
    <td><strong>Page Group</strong></td>
    <td><strong>User Role </strong></td> 
</tr>






    <?php
    foreach($groups as $key=>$value) 
    { ?>    
        <tr bgcolor='#FFFFFF'>
        <td><strong><?php echo $value; ?></strong></td>
        <td>
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group1" value="1" />Viewer
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group2"  value="2" />Approver
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group3" value="3" />Editor
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group3" value="4" />Adder
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group4" value="5" />Super Editor
        <input type="radio" name="group[<?php echo $key; ?>]"  id="chk_group5" value="6" />Blocked
        </td>
        </tr>
    <?php
    } 
    ?>


 </tr>
 <tr></tr> <tr></tr> <tr></tr>
 <tr bgcolor="#FFFFFF">
    <td></td>
    <td>
        <input type="submit" name="submit" value="Submit"/>
    </td>
</tr>

【问题讨论】:

  • 你不需要使用JSON.parse(result);success 处理程序中的 result 参数是一个可以使用的 JSON。
  • 能否给我示例代码,因为我是 Json 新手,谢谢

标签: javascript php jquery html json


【解决方案1】:

使用jquery的each()遍历radio元素集合,使用json提供的值检查匹配的radio值,并将检查添加到匹配的radio。

根据您的 json 为:

{"1":"2","2":"2"} 

在ajax的成功函数中插入下面的代码

success : function(result){
        for(key in result){
         $('input[type=radio]').each(function(){
           if($(this).val() === result[key]){
              $(this).prop('checked', true);
           }
         }
        }
}

【讨论】:

  • user3300466,您可以实现以上代码并根据您的要求进行修改:)
  • 不工作,我试图提醒(contact[key]) 但没有希望;
  • 检查结果,返回什么。它是你给定的 json 格式吗?
  • 让我们以 javascript 变量 var contact = {"1":"1", "2":"2"}; 为例如果您在循环中申请 for(key in contact){alert(contact[key])} 它将显示警报以及值:)
  • 是的,伙计;现在它的工作。请根据更改您的答案。非常感谢:-)
猜你喜欢
  • 1970-01-01
  • 2021-02-26
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2015-08-24
相关资源
最近更新 更多