Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active September 25, 2018 13:31
Show Gist options
  • Select an option

  • Save codetricity/c2036c8b2bf756c577e1a753dd271923 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/c2036c8b2bf756c577e1a753dd271923 to your computer and use it in GitHub Desktop.
Basic d3 and HTML forms

Exercise: D3 and HTML Forms

set up new project

  1. create new project called forms with the following components
    1. d3.js file
    2. index.html file with body tag
    3. main.js file
  2. link index.html file to d3.js and main.js

Create Form

In the HTML file.

  1. create a form with the <form> tag.

  2. create a label element inside of the form

  3. create input of type radio

     <head>
         <meta charset="utf-8">
    
     </head>
    
     <body>
         <form>
             <label>
                 <input type ="radio" name="city_button"
                     value="honolulu" />
                     Honolulu
             </label>
    
          </form>
     </body>
    

button

Create Label For Each City

Separate with a <br> to create a new line for each city.

    <br>
    <label>
        <input type="radio" name="city_button"
            value="chicago" />
            Chicago
    </label>

all cities

select input tag using d3.selectAll

  1. in main.js, create a variable called buttons.

        var buttons
    
  2. assign buttons to the result of d3.selectAll(...

The name of the HTML element you are selecting is called, 'input'.

       var buttons = ... fill in this area ...

create named function getChange

  1. create a named function called, getChange.

     function getChange() ...
    
  2. in the function, output to console.log, this.value.

Note: The value comes from the value of the input label.

form

run function when button state changes

buttons.on("change", getChange);
  • buttons is the variable holding all the input sections
  • on is a special keyword
  • change is a special keyword
  • getChange is the name of the function to run.

Entire Code Listing

    var buttons = d3.selectAll("input");

    function getChange(){
        console.log("Got change to " + this.value);
    }

    buttons.on("change", getChange);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment