Populate input with object value via the key dynamically

Asked

Viewed 56 times

-1

I have a spreadsheet where I need to automatically fill a field from the value entered in another field, where the base is the values of an object.

Example: I have the object:

objeto = {
    10:0.9997,
    11:0.9996,
    12:0.9995
}

When you type 10 into a field, the other field would have the value filled with 0.9997. I already tried to adapt some codes I researched and could not. I appreciate if you can help me.

1 answer

0


Hello, Silvio.

You can do:

var objeto = {
    10: 0.9997,
    11: 0.9996,
    12: 0.9995
}

function mostrarValor(valor) {
    var caixaValor = document.getElementById("caixa-valor")
    if(typeof objeto[valor] !== "undefined") {
        caixaValor.value = objeto[valor]
    } else {
        caixaValor.value = "Valor não encontrado"
    }
}
<p>Chave</p>
<input type='text' onkeyup='mostrarValor(this.value)'>
<p>Valor</p>
<input id='caixa-valor' type='text'>

In this code, we receive the value typed in the text box each time the event keyup happens inside it. Since this number is the very key to the value sought in the object, we just do objeto[chave] and we will have the desired value. After that, just print this value inside the other text box, as you wished.

Additionally, if we insert a key that corresponds to a non-existent value in our object, we will receive a undefined as we make objeto[chave]. To show an error message to the user, we can do an if by checking if objeto[chave] is of the Undefined type.

  • That’s what I wanted to do, I adapted it into my code and it worked fine. Thank you very much!

  • I’m glad it worked :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.