PDA

View Full Version : Javascript unCheck function only working one way



myyoungfamily
05-08-2008, 05:22 PM
Hey guys,
I'm working on a simple javascript function for some checkboxes that I have in a form. If one is checked the other needs to be unchecked. Kind of like a radio button but I need these to be separate inputs. Using the code below, two will uncheck one but one will not uncheck two. What am I doing wrong?



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function unCheck(Form, Name){
document.forms[Form].elements[Name].checked = false;
}
</script>
</head>

<body>
<form name="something">
<input type="checkbox" name="something1" value="1" onclick"javascript:unCheck(this.form.name, 'something2');" /> Something 1
<br />
<input type="checkbox" name="something2" value="1" onclick="javascript:unCheck(this.form.name, 'something1');" /> Something 2
</form>
</body>
</html>

jscheuer1
05-08-2008, 05:29 PM
There are a number of questionable practices here. But the only real problem is that you left out the equals sign in the first onclick event:


<input type="checkbox" name="something1" value="1" onclick"javascript:unChe . . .

should be:


<input type="checkbox" name="something1" value="1" onclick="javascript:unChe . . .

myyoungfamily
05-08-2008, 05:34 PM
HOLY COW!

My membership in the forum should be revoked for that!

How would you recommend doing this?

jscheuer1
05-08-2008, 06:18 PM
XHTML shouldn't be used unless your document really is XHTML/xml which yours was not, and doesn't need to be. Very few need to be. XHTML is just a fad in most cases and does nothing for a page that HTML 4.01 strict does not, and can sometimes cause problems. The XHTML xml standard will most likely be completely revamped before it has any genuine wide application.

That said, converting to valid HTML 4.01 strict, and simplifying the javascript:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function unCheck(el, n){
el.form.elements[n].checked = false;
}
</script>
</head>

<body>
<form name="something" action="#">
<div>
<input type="checkbox" name="something1" value="1" onclick="unCheck(this, 'something2');"> Something 1<br>
<input type="checkbox" name="something2" value="1" onclick="unCheck(this, 'something1');"> Something 2
</div>
</form>
</body>
</html>

myyoungfamily
05-08-2008, 06:58 PM
thanks, it works perfect...