0

I'm new in js please help, the code only return the calculation for the first input in the database. so it prints out the same value for every iteration.

it seems like the loop doesn't break, so it only calculates the first input. I've tried to understand it and kept changing the code but the result is either "NaN" or the first calculation.

const firebaseRef = firebase.database().ref('listing/);

firebaseRef.on("value", function(snapshot){
snapshot.forEach(snap=>{
const listing = snap.val();

document.getElementById("listing").innerHTML += `
<p class=input value=${dB.dBname}></p>
<p class=result></p>
`
})

$(document).each(function(){
    $('.result').html(getAge($('.input').val())+" years");
});

// getAge code from https://stackoverflow.com/questions/10008050/get-age-from-birthdate/10008120

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    
    var age = today.getFullYear() - birthDate.getFullYear();
    
    var m = today.getMonth() - birthDate.getMonth();
    
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="listing"></div>
  • So does this mean you have multiple input/result pairs? If so; you'll need to show a bit more of the html structure in order to see the relationships of these elements to each other. See [mre] – charlietfl Jul 04 '21 at 23:43
  • Welcome to StackOverflow! Here's a tip: *never* put your code snippet before your written description. It says, "I'm too lazy to do any of my own work, and I was just going to dump this code in your lap and demand that you fix, but SO told me that I had to write _something_, so I just wrote a sentence that says how confused I am and how much I want you to fix my problem." It makes people not want to help you. – Tom Jul 05 '21 at 01:10
  • @charlietfl yes I have multiple inputs but the output's value is only based on the first calculation. so they all have the same outputs. I just added the code, I wrote the html inside javascript. I know the calculation Is right because I tested it with '(6)' and all the outputs are based on the 6th element. –  Jul 05 '21 at 04:35
  • @Tom hi I'm really sorry, I didn't know how to submit the question properly. I didn't mean that.. –  Jul 05 '21 at 21:18

0 Answers0