Kolawole Emmanuel Izzy
Kolawole Emmanuel Izzy

Reputation: 1052

How to update a form field as you type in value into another field

Good Day, I'm trying to create a form calculate (a currency converter), in which when you are typing in the value of amount in USD, the other field is updated immediately without clicking any submit button. I have been searching but haven't gotten an answer (maybe due to searching for the wrong keywords).

An Example

<html>
    <form action="">
        <input type="number" name="amountUSD" value="1"><br/>
        <input type="number" name="amountNGN" value="">
    </form>
</html>

What I want to achieve is when the page loads, automatically, the value of amountNGN field should be 365 and of I remove the value of amountUSD field or make the value 0, the 365 in amountNGN field should go away or become 0.

Which makes the calculation: value(amountNGN) = value(amountUSD) * 356; (just an illustration, not sure this language exist).

The value of amountNGN field updates on the fly. Please how can I use JavaScript/jQuery to do this

Thanks

Upvotes: 1

Views: 3682

Answers (3)

JonathanD
JonathanD

Reputation: 1

as I cannot reply in a commment (not enough reputation currently), I try it this way.

For me, the answer given earlier works perfectly, but I have an extra question.

To change the value, the name of the field (name = "amountNGN") is hardcoded. Is there a way to make this dynamic?

I have a container containing all fields name for which I want to get the value from, so I want to loop this container and get the values, but I don't seem to get it working

function convertCurrency(value) {
    // your calculation here
    return (value * 356);
}

$('[name="amountUSD"]').on('change keyup', function() {
    value = $(this).val();
    $('[name="amountNGN"]').val(convertCurrency(value));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
    <input type="number" name="amountUSD" value="1"><br/>
    <input type="number" name="amountNGN" value="">
</form>

Upvotes: 0

Mbotet
Mbotet

Reputation: 180

If you want your server to do this work then use ajax (not recommended, but posible).

If you want to change it on client side JAVASCRIPT will do the job (but then is not a php question); I recommend using the onkeyup javascript event on the field you are working with referencing the one you want to change.

Upvotes: 0

Matt
Matt

Reputation: 1570

I believe this is what you want:

function convertCurrency(value) {
    // your calculation here
    return (value * 356);
}

$('[name="amountUSD"]').on('change keyup', function() {
    value = $(this).val();
    $('[name="amountNGN"]').val(convertCurrency(value));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
    <input type="number" name="amountUSD" value="1"><br/>
    <input type="number" name="amountNGN" value="">
</form>

Upvotes: 4

Related Questions