...

View Full Version : checkbox's problem



rupert
07-30-2011, 03:19 AM
hi all , I'm new to js , here is my problem : i want to make a button to toggle a checkbox , here is my code ,when i replace box.checked with boxVal it doesn't work!


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><button>Toggle checkbox</button></p>
<input type="checkbox" id="box"/>

<script>

var button = document.getElementsByTagName("button")[0];
var box = document.getElementById("box");
var boxVal = document.getElementById("box").checked;

button.onclick = function(){
if (box.checked==false){ //when i replace box.checked with boxVal it doesn't work!
box.checked=true;
}
else if(box.checked==true){
box.checked=false;
}
}

</script>
</body>
</html>

jmrker
07-30-2011, 04:34 AM
boxVal is set during the loading of the script.
It does not change.
When you click on the button a second time, the box.checked will be changed,
but boxVal is never changed after being initialized.

I don't know why you would want to do it this way, but if you MUST use boxVal, then try this:


var boxVal;
button.onclick = function(){
boxVal = box.checked;
if (boxVal==false) { box.checked=true; }
else if(boxVal==true) { box.checked=false; }
}

bullant
07-30-2011, 06:49 AM
This looks at the status of the checkbox and then sets it to the opposite state.



<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><button>Toggle checkbox</button></p>
<input type="checkbox" id="box"/>
<script type="text/javascript">
var btn = document.getElementsByTagName("button")[0];
var box = document.getElementById('box');
btn.onclick = function(){
box.checked = (box.checked)? false : true;
}
</script>
</body>
</html>

rupert
07-31-2011, 12:01 PM
i don't know why boxVal is different from box.checked as i make that boxVal = box.checked . at last i work it out , just to put "box.checked=boxVal" in the end of the function.


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><button>Toggle checkbox</button></p>
<input type="checkbox" id="box"/>

<script>

var button = document.getElementsByTagName("button")[0];
var box = document.getElementById("box");
var boxVal = box.checked;

button.onclick = function(){
if (boxVal==false){boxVal=true;}
else if(boxVal==true){ boxVal=false;}
box.checked=boxVal
}

</script>
</body>
</html>

jmrker
07-31-2011, 04:41 PM
i don't know why boxVal is different from box.checked as i make that boxVal = box.checked . at last i work it out , just to put "box.checked=boxVal" in the end of the function.

...

I indicated the problem in post #2.

Setting the checkbox after testing it only reflects the previous state of the checkbox, not the current.

rupert
08-01-2011, 12:30 AM
I indicated the problem in post #2.

Setting the checkbox after testing it only reflects the previous state of the checkbox, not the current.

yes, i see ! thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum