Nathan Cheval
Nathan Cheval

Reputation: 823

Javascript execute onkeyup function

I have the following input in HTML :

<div class="form-group">
    <label for="siretNumber">Numéro de SIRET</label>
    <input onkeyup="checkSIRET(this);" onfocusout="ocr_on_fly(true, this, true)" onfocusin="ocr_on_fly(false, this, true);" type="text" class="form-control" id="siretNumber" value="{{ pdf['siret'] }}">
</div>
<div class="form-group">
     <label for="sirenNumber">Numéro de SIREN</label>
     <input onkeyup="checkSIREN(this)" onfocusout="ocr_on_fly(true, this, true)" onfocusin="ocr_on_fly(false, this, true)" type="text" class="form-control" id="sirenNumber" value="{{ pdf['siret'] }}">
</div>

On the ocr_on_fly function I need to automatically execute the function of the onkeyup attributes. With the following code I get the value of the onkeyup attr but how could I execute it then ?

let attr = input.getAttribute('onkeyup')
// attr = checkSIRET(this); or attr = checkSIREN(this);

Thanks in advance

Upvotes: 1

Views: 1513

Answers (2)

RobbertC5
RobbertC5

Reputation: 118

You could use dispatchEvent to trigger the keyup keyboard event.

input.dispatchEvent(new KeyboardEvent('keyup'));

By triggering the event this way, the this-argument that you pass to your function matches what it would be during a normal keyup event. If needed, you can pass a specific key that should be reported by the event:

input.dispatchEvent(new KeyboardEvent('keyup', {'key':'a'}));

Upvotes: 5

Bruno Farias
Bruno Farias

Reputation: 903

Since you already have the name of the function as a string:

window["functionName"](arguments);

Please refer to this link

Upvotes: 2

Related Questions