Friday, August 03, 2007

html checkbox submitting unchecked value

If you have used checkbox you would know that the checkbox value get submitted with form only if checkbox is checked, this is required by w3 html spec . What if you want to know if a checkbox was already checked when page was rendered and now unchecked by user. Specially if you are using a framework like struts and want to set a value in ActionForm based on checkbox value. Try submitting the form using Java script


<form name=myForm action="something.do" >
<input type=checkbox name=mycheckbox value=test />
...
Your normal form code here
...
<div id="hiddenArea"/>
<input type=button name='submitMyForm' value='submitMyForm' onclick='submitMyForm()'>
</form>

function submitMyForm(){
var hiddenArea = document.getElementById("hiddenArea");
var myCbx = document.myForm.mycheckbox;
if(!mCbx.checked){
var hiddenStr = "<input type=hidden name=mycheckbox value=notest />";
hiddenArea.innerHTML =hiddenStr;
}
document.myForm.submit;
}

No comments: