Javascript – document.getElementById.checked=true not working in chrome

google-chromehtmljavascript

I'm writing a code to select a value from a drop-down list and the radio button will automatically checked itself according to the onClick attribute. The code worked both in Firefox and IE but not in Chrome.

This is the code for the drop-down list:

<select name="c_DOB_year" id="c_DOB_year">
    <option selected="selected">Year</option>
    <option value="2008" onClick="document.getElementById('c_age_2').checked=true;">2008</option>
    <option value="2009" onClick="document.getElementById('c_age_1').checked=true;">2009</option>
    <option value="2010" onClick="document.getElementById('c_age_0').checked=true;">2010</option>
</select>

This is the code for the radio button:

<label>
    <input type="radio" name="c_age" value="4 Years" id="c_age_0" />
    4 Years
</label>

<label>
    <input type="radio" name="c_age" value="5 Years" id="c_age_1" />
    5 Years
</label>

<label>
    <input type="radio" name="c_age" value="6 Years" id="c_age_2" />
    6 Years
</label>

What seems to be the problem? Hope someone can help me. Thanks. 😀

Best Answer

I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:

var d= {
    '2008':'c_age_2',
    '2009':'c_age_1',
    '2010':'c_age_0',
};
var ele = document.getElementById('c_DOB_year');
ele.onchange = function(){
    document.getElementById(d[ele.value]).checked=true;
}