3

I am trying to trigger onclick function by checkbox and link. Here is Demo which works fine. But If I make change by writing onclick/onchange inside checkbox its not working.:

<input type="checkbox" id="mycheckbox" onclick="myChange();"/>

If I call like this then it works fine:

<input type="checkbox" id="mycheckbox">

document.getElementById('mycheckbox').onclick = function(){
 myChange();
};

Not working :( I wanted to work in Javascript only. Not Jquery What is the reason myChange() not being called from inside input tag

7
  • you can check here jsbin.com/catojenupa/1/edit Commented Apr 14, 2015 at 10:11
  • I had checked this demo but not worked in my case :( Commented Apr 14, 2015 at 10:12
  • what do you mean by not working ?? what happens when you click on checkbox Commented Apr 14, 2015 at 10:19
  • 1
    @alok : check I tried jsfiddle.net/mtj0ajgm/5 Commented Apr 14, 2015 at 10:25
  • 2
    Your code should work fine, it may be something related with JSFiddle. You can see your code working fine here Commented Apr 14, 2015 at 10:41

1 Answer 1

1

Check Here your updated code works.

    function myChange(){
    var temp = document.getElementById('mycheckbox');
    document.getElementById('container').style.display = temp.checked ? 'block' : 'none';
};



document.getElementById('loginlink').onclick = function(){
if (document.getElementById('mycheckbox').checked) {
     document.getElementById('mycheckbox').checked = false ;
     myChange();
} else {
document.getElementById('mycheckbox').checked = true ;
    myChange();
}
  
}
    
#container {
    display: none;
}
<div id="container">Check Box is Checked</div>
<br><br>
<label>
    <input type="checkbox" id="mycheckbox" onclick="myChange()"/>
    Show/hide
    <a href="javascript:void(0)" id="loginlink" >Click Me</a>

</label>

Check Fiddle.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this is what I was looking for. But Why you have put script tag in html tab?
In JSFiddle that way it is working. I don't know much about JSFiddle.
Ok let me check this works in my project this way or not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.