Home > OS >  Trying to create a button that doubles an input
Trying to create a button that doubles an input

Time:09-16

I'm trying to create a button in Javascript that doubles a number inputted by the user. When first opened, the number 1 would be the first number displayed in the textbox. However, I can't seem to get my program to work. Could anyone help me?

function setup() {
  num = document.getElementById("value").value
  document.getElementById("double").innerHTML = num * 2;
  // Write your code here.
}

// Example case. 
document.body.innerHTML = `
<form>
  <input id="value" type="text" value="1"/>
  <input id="double" type="button" value="Double"/>
</form>`;

setup();

document.getElementById("double").click();
console.log(document.getElementById("value").value);

Use value instead of innerHTML for updating button text.

document.getElementById("double").value = num * 2;

Add an event listener for input to update the values each time user change the number(keyup).

function setup() {
  let buttonText;
  num = document.getElementById("value").value
  if(typeof  num != 'number') buttonText = 'Enter numeric value'
  else buttonText=  num*2
  document.getElementById("double").value = buttonText;
  // Write your code here.
}

// Example case. 
document.body.innerHTML = `
<form>
  <input id="value" type="number" value="1"/>
  <input id="double" type="button" value="Double"/>
</form>`;

setup();

document.getElementById('value').addEventListener('keyup', () => {
  setup()
});

document.getElementById("double").click(); 
console.log(document.getElementById("value").value);

CodePudding user response:

There is a much simpler way to do it, that works perfectly: https://jsfiddle.net/ryhmf5tc/5/

function setup() {
    var num;
}

setup();

document.getElementById('double').onclick = function() {
    num = document.getElementById("value").value * 2;
    console.log(num);  
  document.getElementById("output").innerHTML = num;
};

function setup() {
    var num;
}

setup();

document.getElementById('double').onclick = function() {
    num = document.getElementById("value").value * 2;
    console.log(num);  
  document.getElementById("output").innerHTML = num;
};
<form>
  <input id="value" type="text" value="1"/>
  <input id="double" type="button" value="Double"/>
  <p id = output></p>
</form>

CodePudding user response:

You can use value instead of innerHtml

function setup() {
  num = document.getElementById("value").value
  document.getElementById("double").value = num * 2;
  // Write your code here.
}

// Example case. 
document.body.innerHTML = `
<form>
  <input id="value" type="text" value="1"/>
  <input id="double" type="button" value="Double"/>
</form>`;

setup();

document.getElementById("double").click();
console.log(document.getElementById("value").value);

  • Related