dylan42 Posted September 22, 2014 Share Posted September 22, 2014 In javascript How can I check a checkbox dependant on a variable i.e if Var x is “yes” check the checkbox (tick) Else don’t check the checkbox (leave the checkbox empty) Many thanks Link to comment Share on other sites More sharing options...
dylan42 Posted September 22, 2014 Author Share Posted September 22, 2014 this is the code - x is 'yes' but the output does not show 'checked' on output ??? <html><head><script>function selectCheckBox(){ var x="yes" if(document.getElementById('x').checked==true) {{} document.frm.id4.checked=true } if(document.getElementById('x').checked==false) { {} document.frm.id4.checked=false }} function selectCheckBox1(){ if(document.getElementById('y').checked==true) { {} document.frm.id3.checked=true } if(document.getElementById('y').checked==false) { {} document.frm.id3.checked=false } }</script> </head><body><form name="form"> x <input type="checkbox" id="id13" name="id3" value="{id3}" ><br>y <input type="checkbox" id="id14" name="id4" value="{id4}"><br></form> </body></html> Link to comment Share on other sites More sharing options...
Ingolme Posted September 22, 2014 Share Posted September 22, 2014 document.getElementBdyId() will select an element by its ID attribute. Your IDs are "id13" and "id14", not "x" and "y". The syntax "document.frm.id3" is obsolete, you should use other methods to access elements, such as document.getElementById() and document.getElementsByTagName(). You can learn more in the DOM tutorial: http://www.w3schools.com/js/js_htmldom.asp It doesn't look like you're using the variable "x" or "y" anywhere, what you really want is the value from the checkbox, not some random variable. You'll have to rely on events to know when a checkbox is changed. You could use the onchange event. The simplest way is this: document.getElementById("id13").onchange = function() { document.getElementById("id3").checked = document.getElementById("id13").checked} Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now