Reputation: 7566
How do I check if an HTML control exists?
This is my code:
var id = ...
if(document.getElementById(id)!=null)
{
//do something
}
if the html control is radio doesn't work.
How is this done?
Upvotes: 2
Views: 22817
Reputation: 540
function validate(ValFrm) {
var len = ValFrm.elements.length;
for (i = 0; i < len; i++) {
if (ValFrm.elements[i].required == "Yes") {
if (ValFrm.elements[i].value == "") {
alert('The ' + ValFrm.elements[i].title + ' is required to contain data.');
ValFrm.elements[i].focus();
return false;
}
}
if (ValFrm.elements[i].type == "radio") {
if (!ValFrm.app[0].checked && !ValFrm.app[1].checked) {
alert('Please accept or deny.');
return false;
}
}
}
}
Upvotes: 1
Reputation: 344291
Further to your comments above, you should use a unique id
for each radio button, but you can use the same name
for your radio group. Consider the following example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Testing document.getElementById()</title>
</head>
<body>
<input type="radio" id="my_radio_1_id" name="my_radios"> My Radio Button 1
<input type="radio" id="my_radio_2_id" name="my_radios"> My Radio Button 2
<script type="text/javascript">
if (document.getElementById('my_radio_1_id')) {
alert('It Exists');
}
</script>
</body>
</html>
It will alert 'It Exists'
as expected.
Upvotes: 9