Chinmay Sarupria Chinmay Sarupria - 4 months ago 11
Javascript Question

Why button generated using javascript is not working properly?

I am creating 3 text boxes and a button using javascript, then adding a listener to the button which then gets the value of the 3 textboxes and returns the largest number.

This is the code I am using to generate text boxes:

var elementID = ['a', 'b', 'c'];

for(i=0; i<elementID.length; i++) {
var inputElement = document.createElement('input');
inputElement.setAttribute('type', 'text');
inputElement.setAttribute('id', elementID[i]);
document.body.appendChild(inputElement);
}


I tried adding the boxes directly in HTML but it returns the same wrong result.

Here is the code for adding button and attaching an event listener:

var eventHandler = function(event) {
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var c = document.getElementById('c').value;

alert(largestNumber(a, b, c));
};

var button = document.createElement('button');
button.setAttribute('id', 'button');
button.textContent = "Submit";
document.body.appendChild(button);
button.addEventListener('click', eventHandler);


And this is the code I use to calculate the largest number:

var largestNumber = function(a, b, c) {
return (((a>b) ?a:b) > c) ? (a>b?a:b):c;
};


At first I thought this might be a problem with the above code so I tried using the good old
if else
but still it didn't work.

The problem is that it returns the wrong number, for example - if I type 63 in the first box, 210 in second and 57 in third, it will return 63 as the largest number.

Finally here is the working fiddle.

Answer

Your numbers are being compared as string values. Try converting them to numbers first using the parseInt function:

var eventHandler = function(event) {
    var a = parseInt(document.getElementById('a').value);
    var b = parseInt(document.getElementById('b').value);
    var c = parseInt(document.getElementById('c').value);

    alert(largestNumber(a, b, c));
};

var largestNumber = function(a, b, c) {
  return (((a > b) ? a : b) > c) ? (a > b ? a : b) : c;
};

var elements = [{
  id: 'a',
  val: 63
}, {
  id: 'b',
  val: 210
}, {
  id: 'c',
  val: 57
}];
for (i = 0; i < elements.length; i++) {
  var inputElement = document.createElement('input');
  inputElement.setAttribute('type', 'text');
  inputElement.setAttribute('id', elements[i].id);
  inputElement.value = elements[i].val;
  document.body.appendChild(inputElement);
}

var eventHandler = function(event) {
  var a = parseInt(document.getElementById('a').value);
  var b = parseInt(document.getElementById('b').value);
  var c = parseInt(document.getElementById('c').value);

  console.log(largestNumber(a, b, c));
};

var button = document.createElement('button');
button.setAttribute('id', 'button');
button.textContent = "Submit";
document.body.appendChild(button);
button.addEventListener('click', eventHandler);