简体   繁体   English

使用jQuery基于下拉选择选择单选按钮

[英]select radio button based on dropdown selection using jquery

In the below code, if I select try1,it should search db and display corresponding value in input box as well as radio button. 在下面的代码中,如果我选择try1,它将搜索db并在输入框中显示相应的值以及单选按钮。 Here input box value is displayed correctly but radio button is not working. 此处输入框值正确显示,但单选按钮不起作用。 Need help 需要帮忙

Script: 脚本:

$("#test1").change(function()
    {
        $.post('test_file.php', {test_name: $(this).val() },
        function(opt){
        $("#name33").val(opt.test_code);
        $('#ok').val(opt.test_code2);
        }, 'json');

    }); 

Html: HTML:

<table><tr>
<td>
<select name="test1" id="test1" >
<option >try1</option>
<option >try2</option>
</select>
</td>
<td>
<input type="text" name="name33" id="name" />
</td>
<td>
<input type="radio" name="ok" id="ok" value="ok"/>ok
<input type="radio" name="ok" id="ok" value="not_ok"/>Not ok                
</td>

test_file.php test_file.php

$db_sql = $db->queryUniqueObject("SELECT * FROM client WHERE test_name='".$_POST['test_name']."'" );
$test_code1=$db_sql->name;
$test_code2=$db_sql->try;

if($db_sql!=NULL)
{
$arr = array ("test_code1"=>"$test_code1","test_code2"=>"$test_code2");
echo json_encode($arr);
}
else
{
$arr1 = array ("no"=>"no");
echo json_encode($arr1);

}

Use 采用

if(opt.test_code2=="ok")
{
  $('input:radio[value=ok]').prop("checked",true);
}
else if(opt.test_code2=="not_ok")
{
  $('input:radio[value=not_ok]').prop("checked",true);
}

Instead Of 代替

$('#ok').val(opt.test_code2);

Because you set only value using .val() function and id of radio button is not unique so you have to take radio value as selector. 因为您仅使用.val()函数设置值,并且单选按钮的id不唯一,所以您必须将radio value用作选择器。 If you want to checked your radio button according to its value then you have to use .prop() function. 如果要根据单选按钮的值进行检查,则必须使用.prop()函数。

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM