IE, getElementById, and radio buttons
Some simple code:
<input type="radio" id="knob-reassign-leave" name开发者_StackOverflow社区="knob-reassign" value="n" checked="checked">Leave <br>
<input type="radio" id="knob-reassign-cmp" name="knob-reassign" value="d"> Default <br>
<input type="radio" id="knob-reassign" name="knob-reassign" value="r"> Reassign to
<select name="assigned_to" id="assigned_to" onchange="
if ((this.value != 'currentuser') && (this.value != '')) {
var kr = document.getElementById('knob-reassign');
document.getElementById('knob-reassign').checked=true;
}">
<option value="otheruser">Someone Else</option>
<option value="lastuser">Someone Third</option>
<option value="currentuser" selected="selected">Me</option>
</select>
This all works very well in FF and chrome, but as I always hear when I write code, this doesn't work in IE. It appears that IE is searching 'names' for the ID, or it tries to translate the ID into a name, because it always selects the first radio, when it should grab the last.
IE6/7/8 do indeed seem to select the first <input>
element when the name and ID are the same. Here is a simple test case:
<input type="radio" id="a" name="c" value="1">
<input type="radio" id="b" name="c" value="2">
<input type="radio" id="c" name="c" value="3">
<script type="text/javascript">
// Should get 3rd <input> with id 'c' and alert '3'
// Instead finds 1st input with name 'c' and alerts '1'
alert(document.getElementById('c').value);
</script>
While I can't offer an explanation (Google has tons of relevant results), I can offer a fix: Either override IE's implementation of getElementById or change the ID of the last element to be different from the name:
<input type="radio" id="knob-reassign-leave" name="knob-reassign" value="n" checked="checked">Leave <br>
<input type="radio" id="knob-reassign-cmp" name="knob-reassign" value="d"> Default <br>
<input type="radio" id="knob-reassign-reassign" name="knob-reassign" value="r"> Reassign to
<select name="assigned_to" id="assigned_to" onchange="
if ((this.value != 'currentuser') && (this.value != '')) {
document.getElementById('knob-reassign-reassign').checked=true;
}">
<option value="otheruser">Someone Else</option>
<option value="lastuser">Someone Third</option>
<option value="currentuser" selected="selected">Me</option>
</select>
精彩评论