Home » Javascript » html: Onfocus, onblur, onkeypress is not working when used innerhtml while creating row for table

html: Onfocus, onblur, onkeypress is not working when used innerhtml while creating row for table

Posted by: admin August 19, 2018 Leave a comment

Questions:

I am trying to add a row to my table with each cell having an input of type text. But

Onfocus, onblur, onkeypress

are not working on the inputs of the newly created row. Following is my javascript code to add a row to the table:

function Addrow(){  
    var table = document.getElementById("myTable");
    var row = table.insertRow(3);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);

    cell1.innerHTML =
        '<td><input type="text" class="form-control" name="cell1' 
        + counter + '" id="cell1' + counter + '" value="0.0" '
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;" 
        onblur="this.value = this.value==""?"0.0":this.value;"
        onkeypress="return isNumberKey(event)" /></td>';
    cell2.innerHTML = 
        '<td> <input type="text" class="form-control" name="cell2'
        + counter + '" id="cell2' + counter + '" value="0.0"'
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;" 
        onblur="this.value = this.value==""?"0.0":this.value;" 
        onkeypress="return isNumberKey(event)" /></td>';
    cell3.innerHTML = '<td> <input type="text" class="form-control" name="cell3' 
        + counter + '" id="cell3' + counter + '" value="0.0"'
        + ' onfocus="this.value = this.value=="0.0"?"":this.value;" 
        onblur="this.value = this.value==""?"0.0":this.value;" 
        onkeypress="return isNumberKey(event)" /></td>';
    return false;
}

Javascript function to check if input is number or not

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57) {
        alerts("Numbers or Decimal only!!!");
        return false;
    }
        return true;
    }
Answers: