How do I use textfield with button in p5?

There is an example in DOM category call Input Bottom. I am trying to make something similar using html. For some reason my code does not work.For html I have:

<h1>What is your name?</h1>

<input type="text" class="tf">

<button type="button" class="btn">Click Me!</button> 

in js file I have:



var input, button, greeting;

function setup() {
  noCanvas();

  input = select('tf');
  
  button = select('btn');
  button.mousePressed(greet);
}

function greet() {
  greeting.html('hello ' + input.value() + '!');
}

Answers

  • edited May 2017

    My question does not seem too clear... Anyways, I found my answer.

    <h1 class="words">What is your name?</h1>
    
    <input type="text" class="tf">
    
    <button type="button" class="btn">Click Me!</button> 
    

    
    var input, button, txt;
     
    function setup() {
      noCanvas();
     
      input = select('.tf');
       
      button = select('.btn');
      button.mousePressed(greet);
      
      txt = select('.words');
    }
     
    function greet() {
      txt.html('hello ' + input.value() + '!');
    }
    
    
    
  • Instead of class, I would use the id field and select them by using select('#name') instead of select('.name').

    Kf

  • I dont understand why that would be different... I am a nub. Could you explain

  • edited May 2017 Answer ✓

    Maybe because multiple stuff in html can share the same class name which can lead to bugs and ids are specific?

    Thanks for suggestion.

  • Answer ✓

    The id field needs to be unique when used. On the other hand, elements can share a class tag and you can select multiple elements this way. For more info,

    https://github.com/processing/p5.js/wiki/Beyond-the-canvas

    An example interacting with multiple elements via class field: https://p5js.org/examples/dom-modifying-the-dom.html

    Kf

Sign In or Register to comment.