Add keyup to an input when it is created by javascript and not by html

2

In JavaScript I'm creating a input and I'm adding classes. I want to add a keyup .

// Creacion de input para "monto"
var monto_inp = document.createElement("input");
monto_inp.name = "monto";
monto_inp.placeholder = "Monto";
monto_inp.classList.add('detalle_pago');
monto_inp.classList.add('monto');
    
asked by Kinafune 21.08.2018 в 15:55
source

3 answers

1

If you only want to add to that element, you can do it this way, the $ selector of jquery accepts dynamic elements.

// Creacion de input para "monto"
var monto_inp = document.createElement("input");
monto_inp.name = "monto";
monto_inp.placeholder = "Monto";
monto_inp.classList.add('detalle_pago');
monto_inp.classList.add('monto');
$(monto_inp).on('keyup', function() {
        alert('key up');
});
    
answered by 21.08.2018 / 16:13
source
2

An event in Javascript is added with addEventListener :

monto_inp.addEventListener('keyup', function(e) {
    // lo que sea que quieras hacer en el keyup
});

Or like this:

monto_inp.onkeyup = function(e) {
    // lo que sea que quieras hacer en el keyup
});
    
answered by 21.08.2018 в 16:17
1

According to the response of @Dibort to create the event onkeyup is necessary just by calling the item in this case monto_inp and add the evento as you see below.

function createInput() {
    // Creacion de input para "monto"
    var monto_inp = document.createElement("input");
    monto_inp.id = "idInput";
    monto_inp.name = "monto";
    monto_inp.placeholder = "Monto";
    monto_inp.type = "text";
    monto_inp.classList.add('detalle_pago');
    monto_inp.classList.add('monto');
    document.body.appendChild(monto_inp);
    monto_inp.onkeyup = function() {console.log("onkeyup en input");};
}
<!DOCTYPE html>
<html>
   <head>
    </head>
    <body >
         <button onclick="createInput()">Crear input</button>
    </body>
</html>
    
answered by 21.08.2018 в 16:36