views:

59

answers:

2

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?

A: 

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.

Daniel Vassallo
A: 
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;
}
}
}
}
Frode
@Frode... can you format the code by selecting all the code and clicking the little button with the 1s and 0s on it?
Hristo
@Frode: You can use the `101010` button on the toolbar to correctly format your code.
Daniel Vassallo
Thanks for the tip, i noticed Steve already edited it before me :)
Frode