DOM: Checkboxs -- Reading and Setting the Checkmark

Checkboxes are one of those DOM elements you need to create with a few more steps than sliders. I was having trouble reading and setting checkboxes from within processing. Thanks to some help from GoToLoop posted below, I've put together a sketch demonstrating how to use the checkbox.

For people familiar with processing, all you need to know is setting up a checkbox with .attribute("type","checkbox"), accessing it's value, e.g., if (checkbox.elt.checked) not if (checkbox.value() === "on", and elt.click() to programmatically toggle the checkmark.

It defaults to on and there are some fine points with respect to setting it's value via checkbox.value("on") versus checkbox.click().

// p5 JS Checkbox Example
// See http://forum.processing.org/two/discussion/7246/dom-checkboxs-reading-and-setting-the-checkmark
// Thanks to GoToLoop for documenting use of elt w/ DOM Checkbox

var checkbox,chkboxText;  // declare DOM 'elements?'

    function setup() {
      var myCanvas = createCanvas(200,100);

      chkboxText = createP("DOM Checkbox");
      chkboxText.position(width/2-46,0);

      checkbox =  createInput(0,1,0);               
      checkbox.attribute("type","checkbox");     
      checkbox.position(width/2,94);
      checkbox.attribute('checked', null);  

      textAlign(CENTER);
      rectMode(CENTER);
      fill(45,145,237,255);
    }

    function draw() {
      background(255);
      if (checkbox.elt.checked) {                           
        stroke(178,190,135,255);
        ellipse(width/2,50,60,48);
        checkbox.value("on");
        } else {
        stroke(210,78,198,255);
        rect(width/2,50,60,48);
        checkbox.value("off");

      }

      text(checkbox.value(),width/2+40,100);   
      chkboxText.html("DOM Checkbox: " + checkbox.value());


    }

    function keyTyped() {
        if (key === 'c') {
           checkbox.value("off");
        } else
        if (key === 'C') {
           checkbox.value("off");
           checkbox.elt.click();
        }
        if (key === 'd') {
           checkbox.value("on");
        } else
        if (key === 'D') {
           checkbox.value("on");
           checkbox.elt.click();
        } else
        if (key === 'g') {
           checkbox.elt.click(); 
        }        
    }

Here is a link to this script on JS Fiddle: http://jsfiddle.net/loonybomber/zv5vbqud/

Answers

  • edited November 2014 Answer ✓

    I'm also trying to learn JavaScript & p5.js now! #:-S
    Made some research and got the conclusion that for many regular browser stuff we're gonna need DOM:
    http://p5js.org/reference/#/libraries/p5.dom

    Especially that strange p5.Element's elt, kinda DOM nodes: http://p5js.org/reference/#/p5.Element/elt

    For checkbox types, elt.checked seems essential in order to get its check mark status! :(|)
    elt.checked is a boolean getter/setter from HTMLInputElement::checked:
    http://api.kde.org/4.1-api/kdelibs-apidocs/khtml/html/classDOM_1_1HTMLInputElement.html#0d39c56d80aacad53da05fcfad7146a0


    Other good 1s r:

    1. elt.onclick & elt.onchange to assign a function callback event for every click.
    2. elt.clientWidth & elt.clientHeight, elt.offsetWidth & elt.offsetHeight to get button's dimensions.
    3. elt.getBoundingClientRect().width & elt.getBoundingClientRect().height works too.


    1. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers
    2. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
    3. https://developer.mozilla.org/en-US/docs/Web/API/Element


    Perhaps there are better approaches. But for now, that's what I've come up w/: 8-}

    // forum.processing.org/two/discussion/7246/
    // dom-chkboxs-reading-and-setting-the-checkmark
    
    const chkbox = createInput().attribute('type', 'checkbox')
    //.attribute('checked', null);
    
    function setup() {
      createCanvas(150, 150);
      smooth().frameRate(20).rectMode(CENTER).noLoop();
    
      fill(45, 145, 240);
      noStroke();
    
      chkbox.position(width - chkbox.elt.offsetWidth >> 1, height*3 >> 2);
      (chkbox.elt.onchange = display)();
    
      print(Object.getPrototypeOf(chkbox.elt));
      print(Object.getOwnPropertyDescriptor(chkbox.elt, 'checked'));
    }
    
    function display() {
      background(0);
    
      chkbox.elt.checked
        && ellipse(width>>1, 0100, 0100, 060)
        || rect(width>>1, 0100, 0100, 060);
    }
    
  • edited September 2014 Answer ✓

    Thank you for a great response. I like your links and am pleased to know that some of our resources are shared with the KDE api. I am also looking forward to learning more about the elt command and putting graphic monkeys in my comments.

    All I needed to do was change line 24 of my code from " if (checkbox.value() === "on") " to " if (checkbox.elt.checked) " and my code works.

    I need to look into why you used display() instead of draw().

    I like how cleanly if statements can be stated with Booleans.

    I updated the code at jsfiddle

    One thing, I think it's important to note that the checkbox defaults to "on".

    Using the elements, it seems that if you are setting the value of the checkbox programmatically, **you need to use checkbox.elt.click() to simulate a mouseclick **in order for the checkmark to appear.

    I hope no one minds if I also just replace the code in my original post with code incorporating your method. Although there are still things that don't work in my code, e.g. updating the DOM paragraph element text with the state of the checkbox, I think that we have resolved at least one way to interact with the DOM checkbox.

  • edited September 2014

    ... some of our resources are shared with the KDE API.

    Dunno whether KDE API has anything to do w/ JavaScript!
    I believe its QT IDE has support for JavaScript language as that's why they've got reference pages for it!

    ... the elt command...

    It's just a variable pointing to DOM elements I think. Here's what happens when invoking createInput():

    createInput = function (value) {
        var elt = document.createElement('input');
        elt.type = 'text';
        if (value) elt.value = value;
        return addElement(elt, this);
    }
    

    I need to look into why you used display() instead of draw().

    Callback function draw() is continuously invoked by p5.js @ frameRate() FPS:
    http://p5js.org/reference/#/p5/draw
    http://p5js.org/reference/#/p5/frameRate

    But since the canvas only needs to be refreshed w/ new content after the user clicks at the checkbox,
    I've turned draw() off completely w/ noLoop(): http://p5js.org/reference/#/p5/noLoop
    Instead, the checkbox element is bound to my own display() via chkbox.elt.onchange = display! ;;)
    That is, every time its checkmark state changes, display() function is automatically called back! B-)

    If your sketch needs to display an animation while awaiting for the user's click, you gotta re-establish draw()!
    As a quick fix, rename display() back to draw(), delete noLoop(), and finally comment out:
    (chkbox.elt.onchange = display)();.

    ... need to use checkbox.elt.click() to simulate a mouseclick in order for the checkmark to appear.

    Well, I guess it's the user who supposedly should check/uncheck it, ain't it? :(|)
    If you merely wants it to start off checked already, just uncomment .attribute('checked', null);
    just below const chkbox = createInput().attribute('type', 'checkbox') line.
    It's gonna append an extra attribute() to the checkbox element besides previous ('type', 'checkbox').
    Its mere presence makes the checkbox be checkmarked from the get go! :-bd

    Be aware that checked attribute isn't the same as elt.checked! L-) elt.checked stores current checkmark state.
    While checked attribute is just like its "cousin" type, which makes the input to become a checkmark button:
    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input

    See how attribute() actually works :

    attribute = function (attr, value) {
        if (typeof value === 'undefined') {
          return this.elt.getAttribute(attr);
        } else {
          this.elt.setAttribute(attr, value);
          return this;
        }
    }
    

    ... and putting graphic monkeys in my comments.

    If your browser's not blocking it, you can see a smiling emoticon at the top-right of this very reply box!
    Click on it in order to choose 1 of its available emoticons. For example, for monkey, type in: : (|) -> :(|).

    I hope no one minds if I also just replace the code in my original post with code incorporating your method.

    All my learning examples here are public domain. Use and/or modify freely! :-j

Sign In or Register to comment.