Home > Software engineering >  Javascript not creating oninput
Javascript not creating oninput

Time:01-12

I want to create an input through js that will create an HTML element that looks exactly like this: <input id="amount" autocomplete="off" title="amount" value="0" oninput="updateButton();">

Here is my code:

  const parent = document.getElementById('actionButtons');

  let linebreak = document.createElement("br");
  parent.appendChild(linebreak);

  var input = document.createElement('INPUT');
  input.type = 'text';
  input.id = "amount";
  input.class = "amount";
  input.autocomplete = "off";
  input.placeholder = 0;
  input.value = 0;
  input.oninput = updateButton();
  parent.appendChild(input);

This outputs the element: <input type="text" id="amount" autocomplete="off" placeholder="0"> Note that this does not include the oninput. How do I generate the element in my opening statement?

EDIT I needed to get rid of the parentheses to make it input.oninput = updateButton; it works now.

CodePudding user response:

You were almost there with your initial code.

You also wanted to add the title attribute, it is done by the following line input.title = "amount".

Here's the modified code that should work:

const parent = document.getElementById('actionButtons');

let linebreak = document.createElement("br");
parent.appendChild(linebreak);

var input = document.createElement('INPUT');
input.type = 'text';
input.id = "amount";
input.className = "amount";
input.title = "amount";
input.autocomplete = "off";
input.placeholder = "0";
input.value = "0";
input.oninput = updateButton;
parent.appendChild(input);
  • In contrast to class, which is a reserved word in javascript, the property className determines the class of an HTML element.

  • Additionally, since oninput is an event, you only need to assign it rather than call the function.

  • With input, you were doing it correctly.

    updateButton: oninput;

  • It's also important to remember that the value attribute allows you to specify a number or a string, so you could specify 0 or "0" as the value.

  • Related