4

我有以下代码。尝试根据传入的数组值预填充单选按钮。会是1-3

<input name="rating1" type="radio" value="1" />
<input name="rating1" type="radio" value="2" />
<input name="rating1" type="radio" value="3" />

$(document).ready(function() {                         
    //Setting  up the radio buttons                    
    var $radios = $('input:radio[name=rating1]');
        //ratingAnswer is the value I need to select in the radio group. Value=2
    var ratingAnswer=answersArray[oneMap].RATING;
      if($radios.is(':checked') === false) {
        $radios.filter('[value=ratingAnswer]').attr('checked', true);
}

这不会给我任何回报,因为它正在寻找字符串 ratingAnswer 作为值,而不是 ratingAnswer 的变量值。我试过 value=' + ratingAnswer + ' 但它根本不喜欢那样。如何将变量注入该值区域。提前致谢。

4

3 回答 3

6
$radios.filter('[value="' + ratingAnswer + '"]').attr('checked', true);

如果这仍然不起作用,请仔细查看 的值,ratingAnswer看看它是否符合您的预期。

示例:http: //jsfiddle.net/6zAN7/1/

于 2012-09-15T13:13:25.023 回答
2

你应该改变这一行:

 $radios.filter('[value=ratingAnswer]').attr('checked', true);

对于这个:

 $radios.filter('[value='+ratingAnswer+']').attr('checked', true);
于 2012-09-15T13:13:49.427 回答
0

对此的一般解决方案 - 不假设值不会与 jQuery 选择器语法冲突 - 如下:

$radios.filter(function() { return this.value == varWithValueToBeChecked; }).prop('checked', true);
于 2018-04-27T04:21:29.600 回答