我试图用innerHTML输出无线电的价值 但我没有成功。出了什么问题?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
答案 0 :(得分:0)
你可以使用jquery,它会好得多。看看这个例子:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
答案 1 :(得分:0)
它是getElementsByName
(复数)。
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
<强> jsFiddle example 强>
您可能希望将值(userInputgender[i].value;
)返回到div。
答案 2 :(得分:0)
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
答案 3 :(得分:0)
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});