Ok so here it goes im totally lost a bit and im a beg开发者_运维问答inner.
A friend of mine has a radio website, it a really old site.
Has a form where he can uptade the users.
This form has a radio button named dj and values yes or no.
and on the index page it shows the list of the users.
and i would like to do if this radio button is checked, than add a small dj image after the users name.
but no matter what i do im always getting the value null.
the header and footer are included in both of the files, if im right that suppose to give the result no? i placed in the footer its giving back nulll as result
var dj = document.getElementById("dj");
alert(dj.value);
i tried wit the wondow.onload function nothing happens.
I would really like to do this in javascript for practis.
Could somebody please explain what im missing and why i cant get this to show on the index? and is it possible ot make it?
Be gentlle please im a really big beginner :)
Try
alert(dj.checked);
It will alert true or false depending upon the status of radio button if you created your radio button smiler to this
<input type="radio" name="music" value="test" id="dj">
I've created a working example (though not elegant) which illustrates exactly what needs to be done since you've mentioned you're a beginner.
http://sente.cc/misc/radio_button_test.html
The code is:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>radio buttons</title>
<script>
var testit = function(){
var radioyes = document.getElementById('idyes');
var radiono = document.getElementById('idno');
if (radioyes.checked){alert(radioyes.value);}
if (radiono.checked){alert(radiono.value);}
};
</script>
</head>
<body>
<form>
DJ:
<br>
<input id="idyes" type="radio" name="sex" value="yes" /> Yes<br />
<input id="idno" type="radio" name="sex" value="no" /> No
</form>
</body>
<span style="background:lightblue;" onclick="javascript:testit()">click here to run javascript</span>
</html>
There are much better ways of going about this. (like iterating through all the radio elements until you come across one with a .checked
property of true
)
Probably both radio buttons have the same ID, so such code can't work.
Instead, try this: (assuming you have only one form)
var oForm = document.forms[0];
var value = "";
for (var i = 0; i < oForm.elements.length; i++) {
var el = oForm.elements[i];
if (el.type == "radio" && el.name == "dj" && el.checked) {
value = el.value;
break;
}
}
alert("selected value: " + value);
The code is pretty much straightforward.
Live test case.
I would reference the jQuery library and use this code:
$(document).ready(function() {
alert($("#dj").val());
});
精彩评论