I’m a real noob in JavaScript (still on Basic JavaScript part) and I’m trying to build a simple currency converter. I’m getting an Uncaught TypeError: Cannot set property 'innerHTML' of undefined. Here’s the HTML:
function convertToReais(){
var amount = document.getElementById('amount').value;
var result = document.getElementById('result');
result.innerHTML = multiply(amount);
}
function multiply(value){
return value * 3.7;
}
document.getElementById('converter').addEventListener('submit', convertToReais);
I’m doing it on Code Pen too. If anyone can help me please let me know!
function convertToReais(e){
e.preventDefault()
var amount = document.getElementById('amount').value;
// you can convert format value to a number before to Multiplicated
return parseInt(amount) * 3.7;
I found very interesting your work! @nfo94 although i think you might want to add a neat feature, when the user clicks, on the submit button you might want to clear the input value, that way the user wont erase the value.
I decided to add a new function since its what you are trying to define functions. By adding the clearValue() function and invoking it in the convertToReais() function.
function convertToReais(e){
e.preventDefault();
var amount = parseFloat(document.getElementById('amount').value);
var result = document.getElementById('result');
result.innerHTML = 'You\'ve got ' + multiply(amount) + ' reais!';
clearValue();
}
function clearValue(){
document.getElementById('amount').value = '';
};
Glad it works better for you!, also there are endless things you can do to your currency converter, also i see that we can do one more thing to improve it. and that is that when you have no input on the field, and you click on the submit button it said “You’ve got NaN reais!”. thats not good why not just give a message to the user, telling him to actually have an input field. This can be achieved with just adding a validation if else statement to the function convertToReais(e).
function convertToReais(e){
e.preventDefault();
var amount = parseFloat(document.getElementById('amount').value);
var result = document.getElementById('result');
//validate for user input field if it has value or not in the field.
if( document.getElementById('amount').value == "" || document.getElementById('amount').value == null ){
result.innerHTML = 'Please Fill a Input Amount';
}else{
result.innerHTML = 'You\'ve got ' + multiply(amount) + ' reais!';
}
clearValue();
}