1

I am seeing how I can make an Are You Human checkbox, but I am having a problem (Code At The End). I am trying to make it see if it is clicked until it is clicked. I tried onclick, but that is not working.

window.onload = function() {
  var input = document.getElementById('ruhuman');

  function check() {
    if (input.checked) {
      ruhuman.checked = true;
      if (event.originalEvent === undefined) {
        ruhuman.human = false;
      } else {
        ruhuman.human = true;
      }
    }
    alert(ruhuman.human);
    alert(ruhuman.checked);
  }
  input.onchange = check;
  check();

}
<input type="checkbox" id="ruhuman" class="ruhuman" onclick="check()" required="required">
<label>R U Human?</label>

Edit: Thanks for your help! Finished product at http://ruhuman.github.io/.

To the people that answered I can put your github for your help!

arodebaugh
  • 538
  • 1
  • 8
  • 26
  • are you coming up with a browser error? Because you're recursing into the function over and over again and never seem to break out of it – Madivad Dec 14 '15 at 17:35
  • 2
    @Madivad it appears that OP calls the function once the window has loaded and that is all. It doesn't appear to be recursive outside of that. – BuddhistBeast Dec 14 '15 at 17:38
  • 1
    my bad, I missed that it was all inside the on load :( – Madivad Dec 14 '15 at 17:39
  • Have you defined `ruhuman` before window loads? Or are you trying to use a HTML element as a storage object to your own properties? – Teemu Dec 14 '15 at 17:39
  • 1
    I would probably remove the onclick attribute to your input element because it is not necessary to attach the same event twice. – BuddhistBeast Dec 14 '15 at 17:42

2 Answers2

2

originalEvent is JQuery, not JavaScript. A workaround is to test screenX and screenY -- if it's a human, these will have some value based on the checkbox position. Also, you can remove the onclick from your html and tie your click event like this:

document.getElementById ("ruhuman").addEventListener("click", function(e){
    if (this.checked) {
      ruhuman.checked = true;
      if (e.screenX && e.screenY) {
        ruhuman.human = true;
      } else {
        ruhuman.human = false;
      }
    }
    console.log(ruhuman.human);
    console.log(ruhuman.checked);
  });

JS Fiddle Demo

Community
  • 1
  • 1
devlin carnate
  • 8,309
  • 7
  • 48
  • 82
1

This works: https://jsfiddle.net/rz4pmp5L/3/

var input = document.getElementById('ruhuman');
var ruhuman = 
{
  checked: false
};

function check() 
{
  if (input.checked) 
  {
    ruhuman.checked = true;
  }
  alert(ruhuman.checked);
}

input.onchange = check;
check();

The problem was (at least) that ruhuman was not defined at all.

Swiffy
  • 4,401
  • 2
  • 23
  • 49