开发者

getElementById, radio buttons, and document.write();

开发者 https://www.devze.com 2023-03-25 17:14 出处:网络
Radio buttons and JS suck. Ok now that I got that out of my system here is my problem: I finally got Javascript to acknowledge the radio button\'s value after reading getElementById not playing nice w

Radio buttons and JS suck. Ok now that I got that out of my system here is my problem: I finally got Javascript to acknowledge the radio button's value after reading getElementById not playing nice with Radio Buttons

I can alert the value but document.write(); won't work?

Here is my code:

<html>
<head>
<script type="text/javascript">
function getRadioValue() {
var y=document.getElementById('draftrequirement_2').value;
document.write(y);
return y;
}

window.onload = function() { alert(getRadioValue()); }
</script>
</head>

<body>
<i开发者_StackOverflow中文版nput onchange="checkRadio()" type="radio" name="draftrequirement" value="na" id="draftrequirement_2" />
</body>
</html>


In Firefox 5 and Chrome 12 I see 'na' in both the alert and the document, so the document.write() seems to work in those browsers. The radio input is not present after the window load event, though.

Can I ask you why you are using document.write()? There are many alternatives to manipulating the DOM. From w3schools.com (http://www.w3schools.com/js/js_howto.asp)

Note: Try to avoid using document.write() in real life JavaScript code. The entire HTML page will be overwritten if document.write() is used inside a function, or after the page is loaded. However, document.write() is an easy way to demonstrate JavaScript output in a tutorial.


Do not use document.write(). Ever!

Make your life easier and start using jQuery or similar library for manipulating DOM.

If you need to do it with pure javascript only, this should work:

<html>
<head>
<script type="text/javascript">
function checkRadio() {
var y=document.getElementById('draftrequirement_2').value;
document.getElementById('draftrequirement_2_message').innerHTML = y;
}

</script>
</head>

<body>
<input onchange="checkRadio()" type="radio" name="draftrequirement" value="na"   id="draftrequirement_2" />
<div id="draftrequirement_2_message" />
</body>
</html>


<html> 
<head>
<script type="text/javascript">
function checkRadio() {
var y=document.getElementById('draftrequirement_2').value;
document.write(y);
return y;
}


</script>
</head>

<body>
<input onchange="checkRadio()" type="radio" name="draftrequirement" value="na"     id="draftrequirement_2" />NA
</body>
</html>

Use this it is working

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号