5

试图获得一个表单来加载页面,其中已经检查了之前检查过的收音机(在新加载时)。

该页面的提交内容作为 php 变量保存,我可以将其传递到 javascript 中,其余的应该很简单,但它对我不起作用。

我的代码:

<div class="question">
            <label for="sv_213">Question?</label> 
            <input 
                    class="radio"
                    type="radio" 
                    value="Yes" 
                    name="sv_213" 
                />Yes
            <input 
                    class="radio"
                    type="radio" 
                    value="No" 
                    name="sv_213"
                />No

        </div>

我的JavaScript:

$(function() {
    var $213 = Yes;
    $("input[name='sv_213'][value="$213"]").attr('checked', true);

    });?

在上面的js中

var $213 = <dynamically generated content>

这样它被设置为等于选中的单选按钮的值

这是一个无法正常工作的 js fiddle:http: //jsfiddle.net/CW8AC/

非常感谢您的帮助。

顺便说一句,我的代码是基于这个,以前问过的问题: Set selected radio from radio group with a value

4

3 回答 3

12

您需要在值“是”周围加上引号,因为这是一个字符串,而不是布尔值或数字。

var $213 = "Yes";

Also, you need to add the variable into the selector with +'s like this:

$("input[name=sv_213][value="+$213+"]").attr('checked', true);

Updated fiddle, working: http://jsfiddle.net/CW8AC/1/

Full js code:

$(function() {
    var $213 = "Yes";
    $("input[name=sv_213][value="+$213+"]").attr('checked', true);

    });

Update:## Since jQuery 1.6, you can also use the .prop method with a boolean value (this should be the preferred method):

$("input[name=sv_213][value="+$213+"]").prop('checked', true);

in my case, the .attr() method didnt worked for dynamically selecting the radio button whereas .prop() did.

于 2012-10-10T00:16:10.460 回答
0

And in D3, in case anyone was wondering.

d3.selectAll("input[name='sv_213'][value=" + $213 + "]").property("checked", true);
于 2018-03-13T10:42:46.783 回答
0

A javascript solution would be:- For just two(2) radio buttons:

let radios = document.getElementsByName(nameProperty);
let value = "1";//value you want to compare radio with

if (radios[0].value == value) {
  radios[0].checked = true;
}else{
  radios[1].checked = true;
}

for three or more radio buttons:

let radios = document.getElementsByName(nameProperty);
let value = "1";//value you want to compare radio with

for (let i = 0, length = radios.length; i < length; i++) {
  if (radios[i].value == value) {
    radios[i].checked = true;
    
    // only one radio can be logically checked, don't check the rest
    break;
  }
}
于 2021-09-06T09:45:09.467 回答