选择的单选按钮始终打开

时间:2018-06-04 14:24:34

标签: javascript d3.js radio-button

我创建了包含5个单选按钮的html页面:

<div class='container-fluid'>

    <div class='row'>
        <div class='col' id='vaccine-selector-container' style='background-color:#FFC300;'>
            <div class='custom-control custom-radio custom-control-inline'>
                <input type='radio' id='rb-dtp' name='vaccine-selector' class='custom-control-input' checked>
                <label class='custom-control-label' for='rb-dtp' title='Vaccine against diphtheria, tetanus, pertussis'>DTP</label>
            </div>
            <div class='custom-control custom-radio custom-control-inline'>
                <input type='radio' id='rb-mmr' name='vaccine-selector' class='custom-control-input'>
                <label class='custom-control-label' for='rb-mmr' title='Vaccine against measles, mumps and rubella'>MMR</label>
            </div>      
            <div class='custom-control custom-radio custom-control-inline'>
                <input type='radio' id='rb-pol' name='vaccine-selector' class='custom-control-input'>
                <label class='custom-control-label' for='rb-pol' title='Vaccine against poliomyelitis' title='Vaccine against poliomyelitis'>POL</label>
            </div>
            <div class='custom-control custom-radio custom-control-inline'>
                <input type='radio' id='rb-hib' name='vaccine-selector' class='custom-control-input'>
                <label class='custom-control-label' for='rb-hib'>HIB</label>
            </div>  
            <div class='custom-control custom-radio custom-control-inline'>
                <input type='radio' id='rb-hepB' name='vaccine-selector' class='custom-control-input'>
                <label class='custom-control-label' for='rb-hepB' title='Vaccine against hepatitis b'>HEP B</label>
            </div>
        </div>

        <div class='col' id='showCasesOrNotDivId' style='background-color:#FF5733;'>
        </div>
    </div> 

</div>

现在我正在尝试打印用户更改选择时选择的单选按钮。

var vaccineSelected = 'DTP';
d3.selectAll('input[name=vaccine-selector]').on('change', function() {
    vaccineSelected = this.value;
    console.log('vaccineSelected:', vaccineSelected); // on
});

整个代码HERE

我得到的结果总是on。为什么?问题是什么?

1 个答案:

答案 0 :(得分:1)

您的输入不会设置value属性和MDN puts it

  

如果省略HTML中的value属性,则提交表单数据   分配值&#34; on&#34;小组。

设置value属性:

<input type='radio' id='rb-dtp' name='vaccine-selector' class='custom- control-input' 
    value='DTP'
>

或阅读其他属性,例如id

d3.selectAll('input[name=vaccine-selector]').on('change', function() {
    vaccineSelected = this.id;
    console.log('vaccineSelected:', vaccineSelected); // on
});